Wednesday, July 29, 2015

Service calling and getting data

Simple get service calling class

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONObject;



/**
 * @author navula Service call will get the data from the service as a
 *         JSONObject
 */
public class ServiceCall {

    private static String serviceUrl = ""; //provide service url here
    private static URL url;
    private static URLConnection connection;
    private static BufferedReader reader;

    // lawyers list get service Call
    public static JSONObject getServiceDataObject() {
        JSONObject lawyers = null;
        try {
            url = new URL(serviceUrl);
            connection = url.openConnection();
            reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String jsonText = readAll(reader);
            lawyers = new JSONObject(jsonText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lawyers;

    }

    public static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }
}