如何检查URL是否为图片URL,必须为PNG,GIF,JPG格式
我看到可以使用以下代码完成
:URLConnection connection = new URL("http://foo.bar/w23afv").openConnection();
String contentType = connection.getHeaderField("Content-Type");
boolean image = contentType.startsWith("image/");
但是,我需要使用Glide
或OKHttpClient
进行检查。
如何使用上述两种技术实现这一目标?
答案 0 :(得分:2)
如果您对HEAD
的请求满意,我认为Jeff Lockhart是最干净的解决方案。无论如何,我在这里在下面发布有关您的问题的更全面的解决方案:
仅使用 okhttp3
implementation 'com.squareup.okhttp3:okhttp:3.14.0'
您还可以访问主体ContentType来检查HEAD
请求的标头。
选中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());
}
}
});
用 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 v4
和 okhttp3
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
,然后您可以采取相应的行动。
答案 1 :(得分:2)
如果您要做的只是检查URL的Content-Type
,而无需实际下载内容,那么HTTP HEAD request是合适的。
HEAD方法与GET相同,除了服务器不得 在响应中返回一个消息正文。包含的元信息 HTTP标头中对HEAD请求的响应应该相同 响应于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
}
答案 2 :(得分:0)
在okHttpClient中,您必须使用以下行作为URL并进行API调用,如果调用成功,则可以检查条件。
例如:-
String url = new URL("http://foo.bar/w23afv").toString();
OkHttpHandler okHttpHandler= new OkHttpHandler();
okHttpHandler.execute(url);
答案 3 :(得分:0)
如果获得图像字符串。您可以使用此String格式方法简单地检查以(jpg或png)结尾的图片网址。
imageString.endsWith("jpg") || imageString.endsWith("png")
答案 4 :(得分:0)
如果您以字符串形式获取“图像路径”,请尝试...
image_extension = image_path.substring(image_path.length() - 3)
然后将此 image_extension 与 png , jpg 和 gif
进行比较