HTTP POST using JSON in Java

前端 未结 11 1160
南笙
南笙 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:13

    Here is what you need to do:

    1. Get the Apache HttpClient, this would enable you to make the required request
    2. Create an HttpPost request with it and add the header application/x-www-form-urlencoded
    3. Create a StringEntity that you will pass JSON to it
    4. Execute the call

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

    // @Deprecated HttpClient httpClient = new DefaultHttpClient();
    HttpClient httpClient = HttpClientBuilder.create().build();
    try {
        HttpPost request = new HttpPost("http://yoururl");
        StringEntity params = new StringEntity("details={\"name\":\"xyz\",\"age\":\"20\"} ");
        request.addHeader("content-type", "application/x-www-form-urlencoded");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
    } catch (Exception ex) {
    } finally {
        // @Deprecated httpClient.getConnectionManager().shutdown(); 
    }
    

提交回复
热议问题