![](/img/trans.png)
[英]server returns java.io.IOException: Server returned HTTP response code: 400 for URL
[英]Server returned HTTP response code: 400 for URL : java.io.IOException
我究竟做错了什么? 请看一下代码。
HttpURLConnection conn = (HttpURLConnection) new URL(http_url).openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
/*
java.io.IOException: Server returned HTTP response code: 400 for URL: http_url
at sun.net.www.protocol.http.HttpURLConnection.getInputStream
*/
如果我在浏览器中打开http_url,它就可以正常工作。
您没有连接(来自http://alvinalexander.com/blog/post/java/how-open-url-read-contents-httpurl-connection-java的下一个代码)。
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// just want to do an HTTP GET here
connection.setRequestMethod("GET");
// uncomment this if you want to write output to this url
//connection.setDoOutput(true);
// give it 15 seconds to respond
connection.setReadTimeout(15*1000);
connection.connect();
// read the output from the server
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
因为我收到了Java错误而不是错误负载,所以我感到困惑。 稍后,当我在邮递员中检查http_url时,它显示了错误的有效负载以及响应代码400。如果有效负载可用,浏览器将不显示响应代码。 实际上,如果响应代码> = 400,我应该使用conn.getErrorStream()
代替conn.getInputStream()
。
您必须遵循HTTP协议,并设置服务器期望在读取响应之前获得的所有HTTP标头。 肯定您错过了一个或多个标头,例如content-type,accept等。也可能服务器不喜欢Java代理标头,并且喜欢IE,Chrome,Firefox等的代理。所以服务器是正确的,您的请求很糟糕:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.