Tuesday, April 12, 2011

REST in Java

You may want to call the REST web service from Java. Following is the code for a simple Web Service client for the flickr web services interface.

pacage com.vaani.rest;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class FlickrClient {
    public static void main(String[] args) {
        String flickrURL = "http://api.flickr.com/services/rest/?method=flickr.test.echo&name=value&api_key=[yourflickrkey]";
        try {
            SocketAddress addr = new InetSocketAddress("[proxy]", 9090);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
            URL u = new URL("http://api.flickr.com/services/rest/?method=flickr.test.echo&name=value&api_key=[yourflickrkey]");
            HttpURLConnection uc = (HttpURLConnection) u.openConnection(proxy);
            uc.setRequestProperty("Accept", "*/*");
            uc.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
            uc.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
            uc.setRequestProperty("Keep-Alive", "300");
            uc.setRequestProperty("ucection", "keep-alive");
            String proxyUser = "[netUserId]";
            String proxyPassword = "[netPassword]";
            uc.setRequestProperty("Proxy-Authorization", "NTLM " + new sun.misc.BASE64Encoder().encode((proxyUser + ":" + proxyPassword).getBytes()));
            DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = docBuilder.parse(uc.getInputStream());
            System.out.println(doc.getDocumentElement().getTagName());
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment

Chitika