HTTP POST using JSON in Java

前端 未结 11 1003
南笙
南笙 2020-11-22 07:24

I would like to make a simple HTTP POST using JSON in Java.

Let\'s say the URL is www.site.com

and it takes in the value {\"name\":\"mynam

11条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 08:09

    @momo's answer for Apache HttpClient, version 4.3.1 or later. I'm using JSON-Java to build my JSON object:

    JSONObject json = new JSONObject();
    json.put("someKey", "someValue");    
    
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    
    try {
        HttpPost request = new HttpPost("http://yoururl");
        StringEntity params = new StringEntity(json.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        httpClient.execute(request);
    // handle response here...
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpClient.close();
    }
    

提交回复
热议问题