Wednesday, March 12, 2014

HTTP POST request with JSON String in JAVA for Raspberry Pi - libhttpclient-java

Hi there,
Continuing with the last project I want to send the data collected by the Raspberry Pi to my API service. I need to do that using JAVA, so I decided to use libcommons-httpclient-java , a Java library for creating HTTP clients.

Let's install it:

pi@raspberrypi ~ $ sudo apt-get install libhttpclient-java
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
  libhttpcore-java
The following NEW packages will be installed:
  libhttpclient-java libhttpcore-java
0 upgraded, 2 newly installed, 0 to remove and 0 not upgraded.
Need to get 671 kB of archives.
After this operation, 892 kB of additional disk space will be used.
Do you want to continue [Y/n]? 

...


We can compile using this library (javac -cp ...) or include the new library in ore CLASSPATH variable:

$ export CLASSPATH=$CLASSPATH:/usr/share/java/httpclient.jar
$ export CLASSPATH=$CLASSPATH:/usr/share/java/httpcore.jar
$ export CLASSPATH=$CLASSPATH:/usr/share/java/commons-logging-1.1.1.jar


Now, it's time to code the java http client which post the data to the server (not explained in this post).

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

import java.util.List;
import java.util.ArrayList;

public class ApacheHttpClientPost {
    public static final int HTTP_OK = 200;
    private String restUrl="http://192.168.188.20/arest/serverside.php";
   
    public void setRestUrl(String url) {
        this.restUrl = url;
    }
   
   
    public int sendJson(String jsonString) {

        int responseStatusCode = -1;
       
        try {

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(this.restUrl);

            List nameValuePairs = new ArrayList(1);
            nameValuePairs.add(new BasicNameValuePair("tel", jsonString));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpClient.execute(post);


            responseStatusCode = response.getStatusLine().getStatusCode();
            System.out.println(responseStatusCode);
            if (responseStatusCode > 200 && responseStatusCode < 300) {
                throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
            }
   
            BufferedReader br = new BufferedReader(
                new InputStreamReader((response.getEntity().getContent())));
   
            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
   
            httpClient.getConnectionManager().shutdown();
           
        } catch (MalformedURLException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return responseStatusCode;
    }
   
    public static void main(String[] args) {
        ApacheHttpClientPost me = new ApacheHttpClientPost();
       
        me.sendJson("{data: \"data content\"}");
    }
}


Don't forget to set up a server and change the "restUrl" URL. To compile and execute the code run the next commands:

pi@raspberrypi ~/java $ javac ApacheHttpClientPost.java
pi@raspberrypi ~/java $ java ApacheHttpClientPost

200
Output from Server ....

Array
(
    [tel] => {data: "data content"}
)


Of course, the code works but it is an extract from the project. I recomment you to use it as a reference.

Hope help!





No comments:

Post a Comment