服务器返回的http响应代码: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-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错误而不是错误有效负载。稍后,当我在Postman中检查HTTP_URL时,它显示了错误有效载荷以及响应代码400。浏览器如果有效负载,则不会显示响应代码。实际上,如果响应代码> = 400,我应该使用conn.getErrorStream()而不是conn.getInputStream()

您必须遵循HTTP协议,并设置所有HTTP Headers服务器期望在阅读响应之前获得的所有HTTP Headers。绝对您错过了一个或多个标头,例如内容类型,接受等。也许服务器也不喜欢Java代理标头,并且喜欢IE,Chrome,Firefox等的代理商。因此,服务器是正确的,您的要求不好: - )

最新更新