Consuming PHP Zend Rest API in Java


Share/Save/Bookmark

In my last Weblog entry, I described the steps on developing Rest API in PHP using Zend Framework.

Now we have Rest API ready to be consumed by the client. Let consume it using Java Client.

Before beginning the coding part, we need to download following library.

The Jakarta Commons HttpClient 3.1 Library

http://mirror.olnevhost.net/pub/apache/httpcomponents/commons-httpclient/binary/commons-httpclient-3.1.tar.gz

Apache Commons Logging Library

http://mirrors.kahuki.com/apache/commons/logging/binaries/commons-logging-1.1.1-bin.tar.gz

Apache Commons Codec Library

http://download.nextag.com/apache/commons/codec/binaries/commons-codec-1.3.tar.gz

First of all lets create the new NetBeans project. Select “java” from the project categories and “java Application” from the projects list. Click Next, name your project as “zend_rest_client” and finally click Finish button.

Snap-1

Snap-2

Right click on the Library and Select the Property. Add downloaded Library files using “Add Jar/Folder”.

Snap-3

Click “OK” and then replace the content of Main.Java file with the following code.

package zend_rest_client;

import com.sun.org.apache.xerces.internal.parsers.DOMParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/* @author divyen patel */

public class Main {

    public static void main(String[] args) throws IOException, SAXException {
        String str_REST_SERVER = "http://localhost";
        String str_Port = "80"; //Default Apache Port
        String str_rest_API_page = "weather_rest.php";
        String str_rest_method = "get_temperature";
        String str_rest_method_argument = "zipcode=95035";
        String str_rest_url = str_REST_SERVER + ":" + str_Port + "/" + str_rest_API_page + "?method=" + str_rest_method + "&" + str_rest_method_argument;
        System.out.println("Request URL:" + str_rest_url + "\n");
// Send GET request
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(str_rest_url);
        int statusCode = client.executeMethod(method);
        InputStream rstream = null;
        rstream = method.getResponseBodyAsStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
        String line;
        String xmlString = "";
        while ((line = br.readLine()) != null) {
            xmlString = xmlString + line;
        }
        System.out.println("Request Response:" + xmlString + "\n");
//Parsing XML Response
        DOMParser parser = new DOMParser();
        parser.parse(new InputSource(new StringReader(xmlString)));
        Document document = parser.getDocument();
        System.out.println("Parsing XML Response");
        if (document.getElementsByTagName("status").item(0).getTextContent().equals("passed")) {
            System.out.println("Status: Passed");
            System.out.println("zipcode:" + document.getElementsByTagName("zipcode").item(0).getTextContent());
            System.out.println("tempHigh:" + document.getElementsByTagName("tempHigh").item(0).getTextContent());
            System.out.println("templow:" + document.getElementsByTagName("templow").item(0).getTextContent());
        } else {
            System.out.println("Status: Failed");
        }
    }
}

Finally right click on the project and Build it. You may see some warnings stating “DOMParser is Sun proprietary API and may be removed in a future release”. You can ignore these warnings.

Run the project and see the output in the IDE

Snap-4

You can also test it in the terminal console, using “java -jar <location of the jar file>”

Snap-5

If you have any better solution for consuming REST API in Java, please share with me. I am egar to learn it.

Advertisements

5 thoughts on “Consuming PHP Zend Rest API in Java

  1. Hey Divyen,
    Must Say this is a great work. It will be very useful information & will help a lot to programmers in PHP using Zend Framework. Thanks for sharing such great article.
    Thanks

  2. Hi Pramod,
    There was no particular reason I used HttpClient APIs. Thanks for raising this question.
    Discussions on Stack Overflow suggest HttpUrlConnection is much faster.
    http://stackoverflow.com/questions/643730/httpclient-vs-httpurlconnection/643784
    Whereas following blog entry suggest httpclient APIs should be used in the production environment when high volume of transactions are expected.
    http://openjavafaq.blogspot.com/2009/03/httpclient-vs-httpurlconnection.html

  3. Divyen,
    Actually the reason I was thinking of HttpURLConnection was not just performance (it does help though 🙂 ). The bigger issue I was thinking of is dependencies. When using HttpClient – it follows with a whole bunch of required jars which can start clashing with other jars that might be required – in other words JAR HELL. I just wanted to point out that actually your code can be reused by others without having to worry about all the required jars of HttpClient.
    Pramod

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s