Consuming PHP Zend Rest API in Java

Share/Save/Bookmark<script type="text/javascript">a2a_linkname="Consuming PHP Zend Rest API in Java";a2a_linkurl="http://blogs.sun.com/divyen/entry/consuming_php_zend_rest_api";</script><script type="text/javascript" src="http://static.addtoany.com/menu/page.js"></script>

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-1
Snap-2
Snap-2

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

Snap-3
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
Snap-4

You can also test it in the terminal console, using "java -jar <location of the jar file>"
Snap-5
Snap-5

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

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

Posted by Amish Keshwani on March 25, 2009 at 02:43 PM PDT #

Hi,
Any particular reason for using the HttpClient api instead of just using HttpURLConnection in java.net ?

Pramod.

Posted by Pramod Chandersekhar on April 04, 2009 at 11:59 AM PDT #

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

Posted by Divyen Patel on April 05, 2009 at 08:53 AM PDT #

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

Posted by Pramod Chandersekhar on April 05, 2009 at 10:47 AM PDT #

Thanks Pramod for the nice Tip. I will upload the code without this JAR HELL!

Posted by Divyen Patel on April 06, 2009 at 09:38 AM PDT #

Hi,
very nice Tip :)

Posted by Marcin Pudzianowski on May 22, 2010 at 11:41 PM PDT #

Post a Comment:
  • HTML Syntax: NOT allowed
About

Divyen Patel

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today