检查图像网址是否指向实际图像。URL 中的空格引发问题。

huangapple 未分类评论47阅读模式
英文:

Check if an image URL points to an actual image. Space in URL in causing issue

问题

我正在检查一个URL是否指向实际图像,使用以下代码:

URL obj = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
return (responseCode == HttpURLConnection.HTTP_OK);  // 成功

但是,如果图像URL中有空格,这个函数会返回false,虽然URL是有效的。它没有将空格改成%20。我应该对它做哪些更改?

英文:

I am checking if a URL points to an actual image with the following code:

URL obj = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
return (responseCode == HttpURLConnection.HTTP_OK)  // success

But if the image URL has a space in it, this function is returning false, while the URL is valid. It does not change space to %20. What changes should i make to it?

答案1

得分: 0

使用replaceAll()方法在正则表达式中替换imageUrl中的空格,你觉得怎么样?

英文:

How about you replace spaces in imageUrl in regex with replaceAll() method?

答案2

得分: 0

  1. 检查HTTP.responseCode是否为1XX或2XX代码。如果不是,则该URL不是(可访问的)图像。
  2. 尝试检查响应头:content-type。
英文:

Two parts to this:

  1. Check that the HTTP.responseCode is a 1XX or a 2XX code. If not, the URL isn't an (accessible) image
  2. Try checking the response header: content-type

huangapple
  • 本文由 发表于 2020年4月9日 03:49:28
  • 转载请务必保留本文链接:https://java.coder-hub.com/61108892.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定