Java - 从 HttpURLConnection 读取 POST 抛出响应代码 400
Java - Reading POST from HttpURLConnection throwing response code 400
我正在打开一个 HttpURLConnection
并使用 POST
方法,我正在发送一个 JSON 我从另一个 class 构建的请求。 JSON 的结构正确,因为我已经在调试时对其进行了验证。尝试读取服务器给出的输出响应时抛出异常。这是给定的错误
java.io.IOException: Server returned HTTP response code: 400 for URL:
然而,当我手动尝试从具有 POST
方法 chrome 扩展名的 Web 浏览器输入 Url
时。我可以查看响应并且一切正常。所以我确定它与我建立连接的以下代码有关 read/write.
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
//add request header
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
//mapping objects to json
BatchRequest requestParameters = new BatchRequest(o,d);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(requestParameters);
connection.setDoOutput(true);
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
os.writeBytes(json);
os.flush();
os.close();
// this is where the program throws the exception
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
URL
和 JSON
请求都是正确的,因为它们在我尝试通过浏览器手动连接时有效。
不需要 DataOutputStream。只是:
OutputStream os = con.getOutputStream();
我正在打开一个 HttpURLConnection
并使用 POST
方法,我正在发送一个 JSON 我从另一个 class 构建的请求。 JSON 的结构正确,因为我已经在调试时对其进行了验证。尝试读取服务器给出的输出响应时抛出异常。这是给定的错误
java.io.IOException: Server returned HTTP response code: 400 for URL:
然而,当我手动尝试从具有 POST
方法 chrome 扩展名的 Web 浏览器输入 Url
时。我可以查看响应并且一切正常。所以我确定它与我建立连接的以下代码有关 read/write.
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
//add request header
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
//mapping objects to json
BatchRequest requestParameters = new BatchRequest(o,d);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(requestParameters);
connection.setDoOutput(true);
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
os.writeBytes(json);
os.flush();
os.close();
// this is where the program throws the exception
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
URL
和 JSON
请求都是正确的,因为它们在我尝试通过浏览器手动连接时有效。
不需要 DataOutputStream。只是:
OutputStream os = con.getOutputStream();