如何在java中的http post中发送json对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32782266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I send json object in http post in java
提问by arpit joshi
I want to send a JSON object(Note it should not be converted into a string as the server side code is based on the Spring starter project and has params as (@RequestBody PCAP pcap) )I have my below code but it converts the body into a string which gives me 400 bad request .
我想发送一个 JSON 对象(注意它不应该转换为字符串,因为服务器端代码基于 Spring 启动项目并且参数为 (@RequestBody PCAP pcap))我有下面的代码,但它转换了正文变成一个字符串,它给了我 400 个错误的请求。
private void sendData(String ip){
try{
JSONObject json=new JSONObject();
json.put("time_range", "22-23");
json.put("flow_id", "786");
json.put("ip_a", "192.65.78.22");
json.put("port_a", "8080");
json.put("regex", "%ab");
URL url=new URL("http://"+ip+":8080/pcap");
HttpURLConnection httpcon=(HttpURLConnection)url.openConnection();
httpcon.setDoOutput(true);
httpcon.setRequestMethod("POST");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestProperty("Content-Type", "application/json");
Cookie cookie=new Cookie("user", "abc");
cookie.setValue("store");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestProperty("Cookie", cookie.getValue());
OutputStreamWriter output=new OutputStreamWriter(httpcon.getOutputStream());
System.out.println(json);
output.write(json.toString());
httpcon.connect();
String output1=httpcon.getResponseMessage();
System.out.println(output1);
}catch(Exception e){
}
}
Note: Server side code is
注意:服务器端代码是
@RequestMapping(value = URIConstansts.PCAP, produces = { "application/json" }, method = RequestMethod.POST)
public ResponseEntity getPcap(HttpServletRequest request,@RequestBody PcapParameters pcap_params )
回答by Ravindra babu
I prefer to continue with HttpURLConnection over HttpClient. Some comments over advantages can be found at this SE question
我更喜欢继续使用 HttpURLConnection 而不是 HttpClient。可以在这个 SE 问题中找到对优势的一些评论
output.write(json.toString());
output.write(json.toString());
should be changed to
应该改为
byte[] jsonBytes = json.getBytes("UTF-8");
output.write(jsonBytes);
output.flush();
Do not forget to call flush() after writing the objectand UTF-8 format should be instructed before write operation.
不要忘记在写入对象后调用flush(),并且在写入操作之前应指示UTF-8 格式。