检查 url 是否是有扩展名限制的图片

Check if the url is image with extension restriction

如何检查 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 进行检查。

如何使用上述两种技术实现这一点?

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

例如:-

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

如果获取图片字符串。您可以使用此字符串格式方法简单地检查以(jpg 或 png)结尾的图像 url。

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

如果您同意 HEAD 请求,我认为 Jeff Lockhart 是最干净的解决方案。无论如何,我post下面是关于你的问题的更全面的解决方案:

只有okhttp3

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

您可以检查 headers 的 HEAD 请求也访问 body ContentType。

headers 勾选到 onResponse()

    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());
            }
        }
    });

interceptor检查headers: 拦截器很好,因为它集中在一个地方,您可以在其中检查url。

    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);

你输入你的okhttpclientinterceptor然后你就可以进行相应的操作了。

如果您只想查看 URL 的 Content-Type,而不实际下载内容,HTTP HEAD request 比较合适。

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

您可以使用 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
}

如果你得到 "Image path" 作为一个字符串,那么试试这个...

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

然后将此 image_extensionpngjpggif