英文:
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
- 检查HTTP.responseCode是否为1XX或2XX代码。如果不是,则该URL不是(可访问的)图像。
- 尝试检查响应头:content-type。
英文:
Two parts to this:
- Check that the HTTP.responseCode is a 1XX or a 2XX code. If not, the URL isn't an (accessible) image
- Try checking the response header: content-type
专注分享java语言的经验与见解,让所有开发者获益!
评论