服务器返回 HTTP 响应代码:URL 的 400:java.io.IOException

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()));

您必须遵循 HTTP 协议,并设置所有 HTTP headers 服务器在读取响应之前期望获得的信息。您肯定错过了一个或多个 headers,例如 content-type、accept 等。也可能服务器不喜欢 Java 代理 header 并且喜欢来自 IE 的代理,Chrome、火狐等 所以服务器是正确的,你的请求是错误的:-)

我很困惑,因为我得到的是 Java 错误而不是错误负载。后来当我在 postman 中检查 http_url 时,它显示了错误负载以及响应代码 400。如果负载可用,浏览器不会显示响应代码。实际上,如果响应代码 >= 400,我应该使用 conn.getErrorStream() 而不是 conn.getInputStream()