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

时间:2022-12-01 16:17:36

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启动项目并且有params(@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 )

2 个解决方案

#1


3  

Here is what you need to do:

这是你需要做的:

  1. Get the Apache HttpClient, this would enable you to make the required request
  2. 获取Apache HttpClient,这将使您能够提出所需的请求
  3. Create an HttpPost request with it and add the header "application/x-www-form-urlencoded"
  4. 用它创建一个HttpPost请求并添加标题“application / x-www-form-urlencoded”
  5. Create a StringEntity that you will pass JSON to it
  6. 创建一个StringEntity,您将JSON传递给它
  7. Execute the call
  8. 执行通话

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
}

#2


2  

I prefer to continue with HttpURLConnection over HttpClient. Some comments over advantages can be found at this SE question

我更喜欢在HttpClient上继续使用HttpURLConnection。关于优势的一些评论可以在这个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 object and UTF-8 format should be instructed before write operation.

在写入对象之后不要忘记调用flush(),并且在写入操作之前应该指示UTF-8格式。

#1


3  

Here is what you need to do:

这是你需要做的:

  1. Get the Apache HttpClient, this would enable you to make the required request
  2. 获取Apache HttpClient,这将使您能够提出所需的请求
  3. Create an HttpPost request with it and add the header "application/x-www-form-urlencoded"
  4. 用它创建一个HttpPost请求并添加标题“application / x-www-form-urlencoded”
  5. Create a StringEntity that you will pass JSON to it
  6. 创建一个StringEntity,您将JSON传递给它
  7. Execute the call
  8. 执行通话

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
}

#2


2  

I prefer to continue with HttpURLConnection over HttpClient. Some comments over advantages can be found at this SE question

我更喜欢在HttpClient上继续使用HttpURLConnection。关于优势的一些评论可以在这个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 object and UTF-8 format should be instructed before write operation.

在写入对象之后不要忘记调用flush(),并且在写入操作之前应该指示UTF-8格式。