HttpURLConnection抛出响应代码400的json Java读帖子
我正在打开一个HttpURLConnection
,并使用POST
方法发送一个JSON请求,从另一个类构建。JSON的结构是正确的,因为我已经在调试时对它进行了验证。尝试读取服务器给出的输出响应时引发异常。这是给出的错误
java.io.IOException: Server returned HTTP response code: 400 for URL:
但是,当我使用chrome扩展名POST
方法从web浏览器手动输入Url
时。我可以查看响应,一切正常。因此,我确信这与我建立连接和读/写的以下代码有关
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
请求都是正确的,因为当我在浏览器上尝试手动连接时,它们可以工作
# 1 楼答案
不需要DataOutputStream。只是: