8

Right now whenever my project do have a web-service at back end. I am used to create my project with this structure/pattern.

Project

  • HttpMethods Package
    • HttpGetThread
    • HttpPostThread
    • HttpMultipartPostThread
  • Interfaces Package
    • IPostResponse

The code I have been writing in my these JAVA files are,

IPostResponse.java

public interface IPostResponse {
    public void getResponse(String response);
}

HttpGetThread.java

public class HttpGetThread extends Thread {

    private String url;
    private final int HTTP_OK = 200;
    private IPostResponse ipostObj;

    public HttpGetThread(String url, IPostResponse ipostObj) {
        this.url = url;
        this.ipostObj = ipostObj;
    }

    public void run() {
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int responseCode = httpResponse.getStatusLine().getStatusCode();
            if (responseCode == HTTP_OK) {
                InputStream inputStream = httpResponse.getEntity().getContent();
                int bufferCount = 0;
                StringBuffer buffer = new StringBuffer();
                while ((bufferCount = inputStream.read()) != -1) {
                    buffer.append((char) bufferCount);
                }
                ipostObj.getResponse(buffer.toString());
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Same way in HttpPost and HttpMultipartPost classes by extending Thread and having one constructor and a run method.

Then,

I implement the interface to one activity and extend that main activity to all other activities and to get response and make call by creating object of Http classes with parameters and call obj.start();


I still believe that : I am lacking many things or this structure is very poor.

I need to know that, for an Android application to implement Web Service calls in mostly all the activities and have code re-usability which Pattern/Structure should I follow?

I just have seen how Facebook make web service call, for example to Login/Logout it's having Login and Logout listeners.

Is there any blog/article/answers which is well-documented for the same? Please, can any user share his/her excellent experience and solution for the same?

I am more interested in "How should my Class and Interface look like, which kind of methods it should have?"

MKJParekh
  • 34,073
  • 11
  • 87
  • 98
  • @CloseVoters http://stackoverflow.com/faq#questions and If you try to understand this Question is not one of the kind like : “I use ______ for ______, what do you use?” .. This is about how to solve the problem in a global and re-usable way that become the most robust and perfect for the solution. – MKJParekh Nov 09 '12 at 07:31
  • 2
    I have presented my approach to a similar question [here](http://stackoverflow.com/a/8697827/570930). That question was about RESTful clients - but the concept is the same. – curioustechizen Nov 09 '12 at 10:03
  • Thanks will surely have a close look on it soon. – MKJParekh Nov 09 '12 at 11:34

2 Answers2

0

1st and for most suggestion is why don't you use Painless Threading i.e. AsyncTask

Now 2nd thing create a re-usable code same like below, you can create as many as methods with Request parameters.

public class JSONUtil {

    private static JSONUtil inst;

    private JSONUtil() {

    }

    public static JSONUtil getInstance() {
        if (inst == null)
            inst = new JSONUtil();
        return inst;
    }

    /**
     * Request JSON based web service to get response
     * 
     * @param url
     *            - base URL
     * @param request
     *            - JSON request
     * @return response
     * @throws ClientProtocolException
     * @throws IOException
     * @throws IllegalStateException
     * @throws JSONException
     */
    public HttpResponse request(String url, JSONObject request)
            throws ClientProtocolException, IOException, IllegalStateException,
            JSONException {

        synchronized (inst) {

            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            post.setEntity(new StringEntity(request.toString(), "utf-8"));
            HttpResponse response = client.execute(post);
            return response;
        }
    }

    public HttpResponse request(String url)
            throws ClientProtocolException, IOException, IllegalStateException,
            JSONException {

        synchronized (inst) {

            DefaultHttpClient client = new DefaultHttpClient();             
            HttpPost post = new HttpPost(url);
            post.addHeader("Cache-Control", "no-cache");
            HttpResponse response = client.execute(post);
            return response;
        }
    }
}
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
  • Thanks, for the suggestion, That I will surely implement, now My main question is that **"How should my Class and Interface look like, which kind of methods it should have?"** – MKJParekh Nov 09 '12 at 05:51
0

I know this is an old question, but still, I would like to answer it to share what I did on my own projects and I will love suggestions from the community on my approach.

HttpClient

If you take look at HttpClient(as Entity for making the request to endpoints ), it is all about request and response. Think in this way.The behavior of Http protocol for "sending request" requires the method, headers (optional), body (optional). Similarly, in return to request, we get the response with the status code, headers, and body. So you can simply have your HttpClient as:

public class HttpClient 
{
    ExecutorService executor = Executors.newFixedThreadPool(5);
     //method below is just prototype 
     public String execute(String method, String url, Map < String, String > headers ) 
     {
          try 
          {
           URL url = new URL("http://www.javatpoint.com/java-tutorial");
           HttpURLConnection huc = (HttpURLConnection) url.openConnection();
           //code to write headers, body if any
           huc.disconnect();
           //return data
          } 
          catch (Exception e) 
          {
           System.out.println(e);
          }
     }

       public String executeAsync(String method, String url, Map < String, String > headers, Callback callback ) 
     {//Callback is Interface having onResult()
         executor.execute(
             new Runnable()
             {
                 void run()
                 {
                    String json= execute(method,url,headers)
                    callback.onResult(json);
                 }
             }
          );
     }
}

This way you don't need to create a class for the separate request. Instead, we will just use the HtttpClient. You must call API on other thread (not on Android's Main thread).

API Structure

Let's say you have resource called User and you need CRUD in your app. You can create interface UserRepository and implementation UserRepositoryImpl

interface UserRepository
{
    void get(int userId, Callback callback);

    void add(String json,Callback callback);

    //other methods
}


class UserRepositoryImp
{
    void get(int userId, Callback callback)
    {
        HttpClient httpClient= new HttpClient();
        //create headers map
        httpClient.executeAsync("GET","/",authHeaders,callback);
    }

    void add(String json,Callback callback)
    {
         HttpClient httpClient= new HttpClient();
        //create headers map
        httpClient.executeAsync("POST","/",authHeaders,callback);
    }

    //other methods
}

Please make note that you should update UI on Android's UI Thread.[above implementation doesn't worry about that]

VIjay J
  • 736
  • 7
  • 14