java post json对象,如何在java中的http post中发送json对象

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 .

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 )

解决方案

Here is what you need to do:

Get the Apache HttpClient, this would enable you to make the required request

Create an HttpPost request with it and add the header "application/x-www-form-urlencoded"

Create a StringEntity that you will pass JSON to it

Execute the call

The code roughly looks like (you will still need to debug it and make it work)

HttpClient httpClient = new DefaultHttpClient(); //Deprecated

HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead

try {

HttpPost request = new HttpPost("http://yoururl");

StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");

request.addHeader("content-type", "application/x-www-form-urlencoded");

request.setEntity(params);

HttpResponse response = httpClient.execute(request);

// handle response here...

}catch (Exception ex) {

// handle exception here

} finally {

httpClient.getConnectionManager().shutdown(); //Deprecated

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值