Close

Not a member yet?Register now and get started.

lock and key

Sign in to your account.

Account Login

Making HTTP POST request of JSON using Apache's HttpClient

21 Jan. 2013 Posted by joe666 in Programming

Another way of implementing a REST talk to a remote API using Java and JSON.

Instead of making a URL encoded request or using a chunk one of binary data here is an example of simply posting a straight JSON string to an HTTP API Server

package somepackage;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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.DefaultHttpClient;
import org.apache.http.entity.ContentType;
import org.apache.http.HttpResponse;
import org.json.simple.parser.JSONParser;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;
import java.util.Map;
 
/**
 *
 * @author joe666
 */
public class SimpleHTTPPOSTRequester {
 
    private String apiusername;
    private String apipassword;
    private String apiURL;
 
    public SimpleHTTPPOSTRequester(String apiusername, String apipassword, String apiURL) {        
        this.apiURL = apiURL;
        this.apiusername = apiusername;
        this.apipassword = apipassword;
    }
 
    public void makeHTTPPOSTRequest() {
        try {
            HttpClient c = new DefaultHttpClient();        
            HttpPost p = new HttpPost(this.apiURL);        
 
            p.setEntity(new StringEntity("{\"username\":\"" + this.apiusername + "\",\"password\":\"" + this.apipassword + "\"}", 
                             ContentType.create("application/json")));
 
            HttpResponse r = c.execute(p);
 
            BufferedReader rd = new BufferedReader(new InputStreamReader(r.getEntity().getContent()));
            String line = "";
            while ((line = rd.readLine()) != null) {
               //Parse our JSON response               
               JSONParser j = new JSONParser();
               JSONObject o = (JSONObject)j.parse(line);
               Map response = (Map)o.get("response");
 
               System.out.println(response.get("somevalue"));
            }
        }
        catch(ParseException e) {
            System.out.println(e);
        }
        catch(IOException e) {
            System.out.println(e);
        }                        
    }    
}

In this very basic example we send a JSON string to the API server, like:

{
   "username": "myusername",
   "password": "mypassword"
}

And we parse a JSON response from the server, like:

{
   "response": {
      "somevalue" : "value"
   }
}

The example uses libraries from Apache HttpComponents. We also use the json-simple library to make the JSON parsing for the response.

Comments