我收到以下代码的"服务器返回的HTTP响应代码:URL的505":
URL url = new URL(fileLocations.get(i));
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
虽然 URL 在浏览器中打开时工作正常。还尝试对网址进行编码,这也不起作用。
网址是:http://52.66.123.140:8080/TATADHPFILES/1239/TDH 项目/149387773752120170504_113201.jpg
可能是什么原因?
505 错误是"不支持 HTTP 错误 505 HTTP 版本"(可能与"java.net"有关。URISyntaxException : 格式错误的 IPv6 地址"(。
我通过编码(URL(并包装 URI 解决了您的问题:
public static void main(String args[]) throws IOException, URISyntaxException {
URI uri = new URI(
"http",
"52.66.123.140:8080",
"/TATADHPFILES/1239/TDH Items/149387773752120170504_113201.jpg",
"Implementation", "Java");
URL url = uri.toURL();
try {
BufferedImage img = ImageIO.read(url);
// --- your original code will also now work ---
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
// ---------------------------------------
System.out.println("tester");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
我能够在System.out.println("tester"(上设置断点(使用Intellij(; - 并且能够查看 img 变量(显示"正确"的图像(。
您的原始代码也可以使用。
我认为问题的根本原因是您对整个字符串进行编码,而不是仅对参数进行编码:
String urlString = "someurl?param1=" + URLEncoder.encode(first, "UTF-8") + "¶m2=" + URLEncoder.encode(second, "UTF-8") ;
使用 URLEncoder 对 url 进行编码
URL url = new URL(fileLocations.get(i));
String encodedURL=java.net.URLEncoder.encode(url,"UTF-8");
System.out.println(encodedURL);