我正在打开一个HttpURLConnection
并使用POST
方法,我发送一个JSON请求,我构建另一个类。 JSON的结构正确,因为我已经在调试时验证了它。尝试读取服务器给出的输出响应时抛出异常。这是给出的错误
java.io.IOException: Server returned HTTP response code: 400 for URL:
但是,当我手动尝试使用Url
方法Chrome扩展程序从网络浏览器输入POST
时。我可以查看响应,一切正常。所以我确信它与下面的代码有关,我在那里进行连接和读/写。
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
请求都是正确的,因为它们在我尝试通过浏览器进行手动连接时起作用。
答案 0 :(得分:1)
不需要DataOutputStream。只是:
OutputStream os = con.getOutputStream();