HTTP POST using JSON in Java HTTP POST using JSON in Java java java

HTTP POST using JSON in Java


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(); }


You can make use of Gson library to convert your java classes to JSON objects.

Create a pojo class for variables you want to sendas per above Example

{"name":"myname","age":"20"}

becomes

class pojo1{   String name;   String age;   //generate setter and getters}

once you set the variables in pojo1 class you can send that using the following code

String       postUrl       = "www.site.com";// put in your urlGson         gson          = new Gson();HttpClient   httpClient    = HttpClientBuilder.create().build();HttpPost     post          = new HttpPost(postUrl);StringEntity postingString = new StringEntity(gson.toJson(pojo1));//gson.tojson() converts your pojo to jsonpost.setEntity(postingString);post.setHeader("Content-type", "application/json");HttpResponse  response = httpClient.execute(post);

and these are the imports

import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.HttpClientBuilder;

and for GSON

import com.google.gson.Gson;


@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();}