检查网址是否为具有扩展限制的图像

问题描述 投票:0回答:5

如何检查URL是否为必须为PNG,GIF,JPG格式的图像URL

我看到可以用这段代码完成:

URLConnection connection = new URL("http://foo.bar/w23afv").openConnection();
String contentType = connection.getHeaderField("Content-Type");
boolean image = contentType.startsWith("image/");

但是,我需要使用GlideOKHttpClient进行检查。

如何使用上面提到的两种技术实现这一目标?

android okhttp okhttp3 android-glide
5个回答
2
投票

如果你对HEAD请求没问题,我认为Jeff Lockhart是最干净的解决方案。无论如何,我在这里发布一个关于你的问题的更全面的解决方案

仅限okhttp3

implementation 'com.squareup.okhttp3:okhttp:3.14.0'

您可以检查HEAD请求的标头,也可以访问正文ContentType。

检查headersonResponse()

    OkHttpClient client = new OkHttpClient();

    Request requestHead = new Request.Builder()
            .url("your tiny url")
            .head()
            .build();

    Request request = new Request.Builder()
            .url("your tiny url")
            .build();

    // HEAD REQUEST
    client.newCall(requestHead).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
            Log.d("OKHTTP3 onFailure", e.getMessage());
        }

        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
            try {
                final ResponseBody _body = response.body();
                if (_body != null) {
                    final MediaType _contentType = _body.contentType();
                    if (_contentType != null) {
                        final String _mainType = _contentType.type(); // image
                        final String _subtypeType = _contentType.subtype(); // jpeg/png/etc.
                        Log.d("OKHTTP3 - media content type", _contentType.toString());
                        Log.d("OKHTTP3 - media main type", _mainType);
                        Log.d("OKHTTP3 - media sub type", _subtypeType);
                        boolean isImage = _mainType.equals("image");
                        Log.d("OKHTTP3 - I'VE GOT AN IMAGE", "" + isImage);
                        if (isImage) {
                            Log.d("OKHTTP3 WE HAVE AN IMAGE!", "yay!");
                        } else {
                            Log.d("OKHTTP3 SKIP CONTENT!", "Buuu!");
                        }
                    }
                }
            } catch (Exception e) {
                Log.d("OKHTTP3 Interrupted Exception", e.getMessage());
            }
        }
    });

    // GET REQUEST
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
            Log.d("OKHTTP3 onFailure", e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            try {
                final ResponseBody _body = response.body();
                final MediaType _contentType = _body.contentType();
                final String _mainType = _contentType.type(); // image
                final String _subtypeType = _contentType.subtype(); // jpeg/png/etc.
                Log.d("OKHTTP3 - media content type", _contentType.toString());
                Log.d("OKHTTP3 - media main type", _mainType);
                Log.d("OKHTTP3 - media sub type", _subtypeType);
                boolean isImage = _mainType.equals("image");
                Log.d("OKHTTP3 - I'VE GOT AN IMAGE", "" + isImage);
                if (isImage) {
                    final InputStream inputStream = response.body().byteStream();
                    final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    runOnUiThread(() -> {
                        helloImageView.setImageBitmap(bitmap);
                    });
                }
            } catch (Exception e) {
                Log.d("OKHTTP3 Interrupted Exception", e.getMessage());
            }
        }
    });

headers检查interceptor:拦截器是好的,因为它集中在你检查你的网址的一个地方。

    OkHttpClient clientWithInterceptor = new OkHttpClient.Builder()
            .addInterceptor(chain -> {
                Response _response = chain.proceed(request);
                final ResponseBody _body = _response.body();
                if (_body != null) {
                    final MediaType _contentType = _body.contentType();
                    if (_contentType != null) {
                        final String _mainType = _contentType.type(); // image
                        final String _subtypeType = _contentType.subtype(); // jpeg/png/etc.
                        Log.d("OKHTTP3 - media content type", _contentType.toString());
                        Log.d("OKHTTP3 - media main type", _mainType);
                        Log.d("OKHTTP3 - media sub type", _subtypeType);
                        boolean isImage = _mainType.equals("image");
                        Log.d("OKHTTP3 - I'VE GOT AN IMAGE", "" + isImage);
                        if (isImage) {
                            return _response;
                        } else {
                            return return415Response(chain);
                        }
                    } else {
                        return return415Response(chain);
                    }
                } else {
                    return return415Response(chain);
                }
            }).build();

    clientWithInterceptor.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
            Log.d("OKHTTP3 onFailure", e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.d("OKHTTP3 - onResponse", "" + response.toString());
            if (response.isSuccessful()) {
                final InputStream inputStream = response.body().byteStream();
                final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                runOnUiThread(() -> {
                    helloImageView.setImageBitmap(bitmap);
                });
            }
        }
    });
    //*/
}

private Response return415Response(Interceptor.Chain chain) {
    return new Response.Builder()
            .code(415) // Media type not supported... or whatever
            .protocol(Protocol.HTTP_1_1)
            .message("Media type not supported")
            .body(ResponseBody.create(MediaType.parse("text/html"), ""))
            .request(chain.request())
            .build();
}

使用Glide v4okhttp3

implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
implementation 'com.github.bumptech.glide:annotations:4.9.0'
implementation "com.github.bumptech.glide:okhttp3-integration:4.9.0"

你需要扩展GlideAppModule

@GlideModule
public class OkHttpAppGlideModule extends AppGlideModule {
    @Override
    public void applyOptions(@NonNull Context context, @NonNull GlideBuilder builder) {
        super.applyOptions(context, builder);
    }

@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
    OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(15, TimeUnit.SECONDS)
            .connectTimeout(15, TimeUnit.SECONDS)
            .addNetworkInterceptor(chain -> {
                Response _response = chain.proceed(chain.request());
                int _httpResponseCode = _response.code();
                if (_httpResponseCode == 301
                || _httpResponseCode == 302
                || _httpResponseCode == 303
                || _httpResponseCode == 307) {
                    return _response; // redirect
                }
                final ResponseBody _body = _response.body();
                if (_body != null) {
                    final MediaType _contentType = _body.contentType();
                    if (_contentType != null) {
                        final String _mainType = _contentType.type(); // image
                        final String _subtypeType = _contentType.subtype(); // jpeg/png/etc.
                        Log.d("OKHTTP3 - media content type", _contentType.toString());
                        Log.d("OKHTTP3 - media main type", _mainType);
                        Log.d("OKHTTP3 - media sub type", _subtypeType);
                        boolean isImage = _mainType.equals("image");
                        Log.d("OKHTTP3 - I'VE GOT AN IMAGE", "" + isImage);
                        if (isImage) {
                            Log.d("OKHTTP3 WE HAVE AN IMAGE!", "yay!");
                            return _response;
                        } else {
                            return return415Response(chain);
                        }
                    } else {
                        return return415Response(chain);
                    }
                } else {
                    return return415Response(chain);
                }
            }).build();

    OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory(client);

    registry.replace(GlideUrl.class, InputStream.class, factory);
}

private Response return415Response(Interceptor.Chain chain) {
    return new Response.Builder()
            .code(415) // Media type not supported... or whatever
            .protocol(Protocol.HTTP_1_1)
            .message("Media type not supported")
            .body(ResponseBody.create(MediaType.parse("text/html"), ""))
            .request(chain.request())
            .build();
}

然后打电话

Glide.with(this)
            .load("your tini url")
            .into(helloImageView);

你输入你的okhttp client interceptor,你可以采取相应的行动。


2
投票

如果您要做的只是检查URL的Content-Type,而不实际下载内容,则HTTP HEAD request将是合适的。

HEAD方法与GET相同,只是服务器不能在响应中返回消息体。响应HEAD请求的HTTP头中包含的元信息应该与响应GET请求时发送的信息相同。该方法可用于获得关于请求所暗示的实体的元信息,而无需转移实体主体本身。此方法通常用于测试超文本链接的有效性,可访问性和最近的修改。

您可以使用OkHttp执行以下操作:

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
        .url("http://foo.bar/w23afv")
        .head()
        .build();

try {
    Response response = client.newCall(request).execute();
    String contentType = response.header("Content-Type");
    boolean image = false;
    if (contentType != null) {
        image = contentType.startsWith("image/");
    }

} catch (IOException e) {
    // handle error
}

0
投票

在okHttpClient中,你必须使用下面的行作为URL并进行API调用,如果调用成功,那么你可以检查你的情况。

例如: -

 String url = new URL("http://foo.bar/w23afv").toString();
 OkHttpHandler okHttpHandler= new OkHttpHandler();
    okHttpHandler.execute(url);

0
投票

如果您获得图像字符串。您可以使用此String格式方法检查以(jpg或png)结尾的图像URL。

imageString.endsWith("jpg") || imageString.endsWith("png")

0
投票

如果您将“图像路径”作为字符串,那么试试这个......

image_extension = image_path.substring(image_path.length() - 3)

然后将此image_extension与png,jpg和gif进行比较

© www.soinside.com 2019 - 2024. All rights reserved.