[英]Server returned HTTP response code: 400 for URL : java.io.IOException
What am I doing wrong? 我究竟做错了什么? Please have a look at code.
请看一下代码。
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
*/
If I open the http_url in browser, it's working. 如果我在浏览器中打开http_url,它就可以正常工作。
You are not connected (next code from http://alvinalexander.com/blog/post/java/how-open-url-read-contents-httpurl-connection-java ). 您没有连接(来自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()));
I was confused since I was getting the Java error instead of the error payload. 因为我收到了Java错误而不是错误负载,所以我感到困惑。 Later when I checked the http_url in postman, it showed the error payload as well as response code 400. Browser doesn't show response code if payload is available.
稍后,当我在邮递员中检查http_url时,它显示了错误的有效负载以及响应代码400。如果有效负载可用,浏览器将不显示响应代码。 Actually I should have used
conn.getErrorStream()
instead of conn.getInputStream()
in case of response code >= 400. 实际上,如果响应代码> = 400,我应该使用
conn.getErrorStream()
代替conn.getInputStream()
。
You have to follow HTTP protocol, and set all HTTP headers server expects to get before reading a response. 您必须遵循HTTP协议,并设置服务器期望在读取响应之前获得的所有HTTP标头。 Definitely you missed one or more headers, like content-type, accept etc. also maybe server does not like Java agent header and likes agents from IE, Chrome, Firefox etc. So server is right, you request is bad :-)
肯定您错过了一个或多个标头,例如content-type,accept等。也可能服务器不喜欢Java代理标头,并且喜欢IE,Chrome,Firefox等的代理。所以服务器是正确的,您的请求很糟糕:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.