Saturday, June 1, 2013

Simple REST Example without Security

I wanted to do one sample project using CouchDB. So I have been looking in to internet for very simple REST example with Java. Could hardly find any. Hope bellow one will help many.

This article is not going to tell what is CouchDB. Assume it as a REST provider. So when I hit a url in browser , it is going to give me a text response.

Following is the REST client which shows how the same url could be fired through JAVA program to obtain the result

------------------------------------------
package course;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class RestClient {

    public final static String endpoint = "http://127.0.0.1:5984/courses/_all_docs";

    public static void main(String[] args) {
        HttpURLConnection request = null;
        BufferedReader reader = null;
        StringBuilder response = null;
        try{
            URL endpointUrl = new URL(endpoint);
            request = (HttpURLConnection)endpointUrl.openConnection();
            request.setRequestMethod("GET");
            request.connect();
            reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
            response = new StringBuilder();
            String line;
            while((line=reader.readLine())!=null){
                response.append(line);
            }
            reader.close();
            request.disconnect();
            System.out.println(response);

         } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
-----------------------------------------------------------------------------

No comments:

Post a Comment