7 Apr 2016

Retrofit 2.0 Android | Web service using Retrofit.

Retrofit is developed by Square, Inc. It is one of the most popular HTTP Client Library for Android as a result of its simplicity and its great performance compare to the others.

A part from development,Old method to using web service which is quite lengthy and time consuming.

Here retrofit set everything for you automatically. Now Lets implement Retrofit in our code.

Step 1 : Create studio project.
Now we will Add Retrofit library to our project : Visit Retrofit Official Site
For Android Studio you just need to paste below line of code under dependency of  build.gradle file.

compile 'com.squareup.retrofit2:retrofit:2.0.1'

Now, Add Another library called Okhttp to our project
compile 'com.squareup.okhttp:okhttp:2.4.0' 

Now, Add two more Library Gson and GsonConverter to build.gradle
compile 'com.google.code.gson:gson:1.7.2' 
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

Now, Add one more lib to display log of request and response from retrofit.
compile 'com.squareup.okhttp:logging-interceptor:2.6.0'

SERVICE : 
Let's take Login service to implement using retrofit. below is the service for user login which have two parameter Username and password.
http://xyz/service/userlogin?Username=xyz&password=abc

Step 2: Create POJO/Class
Now we will make all POJO of JSON data coming from server. in my case here is the JSON response of the server.
{"status":"true","message":"Login successfully","data":{"id":1,"first_name":"Hasmukh","last_name":"Bhadani"}}

POJO class in Retrofit by Most Easiest Way :

  • Visit pojo.sodhanalibrary - This is Official website to Convert JSON Data into POJO class. Just You have to Copy Paste all the Codes. Rename pojo as per your requirement.


Here I am creating Three POJO : (1)BaseResponse (2)LoginResponse. (3)UserInfo

BaseResponse :
It contain common filed which is used for whole server in the project.

  public class BaseResponse {

    private String message;

    private String status;

    public String getMessage ()
    {
        return message;
    }

    public void setMessage (String message)
    {
        this.message = message;
    }

    public boolean getStatus ()
    {
        return status.equalsIgnoreCase("true");
    }

    public void setStatus (boolean status)
    {
        this.status = String.valueOf(status);
    }
}
LoginResponse :
   public class LoginResponse extends BaseResponse
{
    private Data data;
    public Data getData ()
    {
        return data;
    }
    public void setData (Data data)
    {
        this.data = data;
    }
   
}
UserInfo: 
   public class UserInfo
{
     private String id;

    private String first_name;

    private String last_name;

    public String getId ()
    {
        return id;
    }

    public void setId (String id)
    {
        this.id = id;
    }

    public String getFirst_name ()
    {
        return first_name;
    }

    public void setFirst_name (String first_name)
    {
        this.first_name = first_name;
    }

    public String getLast_name ()
    {
        return last_name;
    }

    public void setLast_name (String last_name)
    {
        this.last_name = last_name;
    }
   
}
Step 3: Create RestClient.java
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.logging.HttpLoggingInterceptor;
import com.truckforload.app.AppUrls;
import java.util.concurrent.TimeUnit;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;

public class RestClient
{
    private static ApiInterface restClient;
    static
    {
        setupRestClient();
    }
    private RestClient() {}

    public static ApiInterface get()
    {
        return restClient;
    }
    private static void setupRestClient()
    {
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(10, TimeUnit.SECONDS);

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);

        HttpLoggingInterceptor interceptorBody = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        client.interceptors().add(interceptor);
        client.interceptors().add(interceptorBody);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppUrls.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        restClient = retrofit.create(ApiInterface.class);
    }
}
Step 4: Create ApiInterface.java
Now create an Interface for all http methods and parameter.

import retrofit.Call;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Query;

public interface ApiInterface
{
    // Login
    @GET("service/userlogin")
    Call<LoginResponse> login( @Query("Username") String strUsername, @Query("password") String strpassword);

}
Step 5: Create AppWs.java
It contain all method of project which are used for service.And it will provide response using call back listener.

import retrofit.Call;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;

public class AppWs
{
    private static final String TAG = "AppWs";

    public static String login( final LoginRequest request, final Context context, final WsListener listener )
    {
        String unm= request.getUsername();
        String password = request.getPassword();

        Call<LoginResponse> call = RestClient.get().login(unm, password);
        try
        {
            call.enqueue(new Callback<LoginResponse>()
            {
                @Override
                public void onResponse( Response<LoginResponse> response, Retrofit retrofit )
                {
                    LoginResponse baseResponse = response.body();
                    if ( baseResponse != null && response.isSuccess() )
                    {
                        if ( listener != null )
                        {
                            listener.onResponseSuccess(baseResponse);
                        }
                    }
                    else
                    {
                        if ( listener != null )
                        {
                            ResponseBody errorBody = response.errorBody();

                            if ( errorBody != null )
                            {
                                listener.notifyResponseFailed(errorBody.toString(), null);
                            }
                        }

                    }
                }

                @Override
                public void onFailure( Throwable t )
                {
                    retrofitError(t, listener, context);
                }

            });

        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
        return "";
    }


    public static void retrofitError( Throwable t, WsListener listener, Context context )
    {
        if ( listener != null )
        {
            t.printStackTrace();
            listener.notifyResponseFailed(null, null);
        }
    }

    public interface WsListener
    {
        void onResponseSuccess( BaseResponse baseResponse );

        void notifyResponseFailed( String message, BaseRequest request );
    }
}
Step 6: Create MainActivity.java
Below is the Method which is call on SignIn Button in the activity

private void callServiceLogin()
    {
  ProgressDialog progressDialog = new ProgressDialog(this);
  progressDialog.setMessage("Loading...");
  progressDialog.setCancelable(false);

        LoginRequest loginRequest = new LoginRequest();

        String phone = etUserName.getText().toString();
        loginRequest.setUsername(phone);

        String password = etPassword.getText().toString();
        loginRequest.setPassword(password);

        AppWs.login(loginRequest, this, new AppWs.WsListener()
        {
            @Override
            public void onResponseSuccess( BaseResponse baseResponse )
            {
  if (progressDialog != null && progressDialog.isShowing())
             {
                 progressDialog.dismiss();
             }

                if ( baseResponse instanceof LoginResponse )
                {
                    LoginResponse loginResponse = (LoginResponse) baseResponse;

                    boolean status = loginResponse.getStatus();
                    UserInfo userInfo = loginResponse.getData();
                }
            }

            @Override
            public void notifyResponseFailed( String message, BaseRequest request )
            {
                dismissProgressDialog();                
            }
        });

    }
Here is the official site to get more API interface declaration for service. Visit here.

Find following are the reference links to go in deep for retrofi 2.0 :
https://guides.codepath.com/android/Consuming-APIs-with-Retrofit
http://www.iayon.com/consuming-rest-api-with-retrofit-2-0-in-android/

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

5 Apr 2016

GET/POST request Using HttpURLConnection.

Hi All,

Today I am sharing one of the important code snippet. As we all know  org.apache.http.client.HttpClient,

This interface was deprecated in API level 22. So now onward need to use URLConnection instead.
Means that you should switch to java.net.URL.openConnection().

Here is the http utility class to send GET/POST request to the server.

RestClient :
package com.httpurlconnection;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class RestClient
{
    public enum RequestMethod
    {
        GET,
        POST
    }

    private HashMap<String, String> params;

    private HashMap<String, String> headers;

    private String serviceUrl;

    private int responseCode;

    private String message;

    private String response;

    private InputStream inputStream = null;

    private HttpURLConnection urlConnection = null;

    private String strJson=null;

    public RestClient( String url )
    {
        this.serviceUrl = url;
        params = new HashMap<String, String>();
        headers = new HashMap<String, String>();
    }

    public String getResponse()
    {
        return response;
    }

    public String getErrorMessage()
    {
        return message;
    }

    public int getResponseCode()
    {
        return responseCode;
    }


    public void AddParam( String name, String value )
    {
        params.put(name, value);
    }

    public void AddHeader( String name, String value )
    {
        headers.put(name, value);
    }

    public void AddData( String strJson )
    {
        this.strJson=strJson;
    }

    public void Execute( RequestMethod method ) throws Exception
    {
        switch ( method )
        {
            case GET:
            {
                //add parameters
                String combinedParams = "";
                if ( !params.isEmpty() )
                {
                    combinedParams += "?";
                    for ( Map.Entry<String, String> p : params.entrySet() )
                    {
                        String paramString = URLEncoder.encode(p.getKey(), "UTF-8") + "=" + URLEncoder.encode(p.getValue(), "UTF-8");
                        if ( combinedParams.length() > 1 )
                        {
                            combinedParams += "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }
                try
                {
                    URL url = new URL(serviceUrl + combinedParams);

                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setReadTimeout(15000);
                    urlConnection.setConnectTimeout(15000);

                    /* Add header */
                    if ( !headers.isEmpty() )
                    {
                        for ( Map.Entry<String, String> header : headers.entrySet() )
                        {
                            urlConnection.setRequestProperty(header.getKey(), header.getValue());
                        }
                    }

                    int statusCode = urlConnection.getResponseCode();

                /* 200 represents HTTP OK */
                    if ( statusCode == HttpURLConnection.HTTP_OK )
                    {
                        inputStream = new BufferedInputStream(urlConnection.getInputStream());
                        response = convertStreamToString(inputStream);
                        Log.e("Response ::", response);
                    }
                }
                catch ( Exception e )
                {
                    Log.d("Exception::", e.getLocalizedMessage());
                }
                finally
                {
                    urlConnection.disconnect();
                }
                break;
            }
            case POST:
            {
                try
                {
                    URL url = new URL(serviceUrl);

                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("POST");
                    urlConnection.setReadTimeout(15000);
                    urlConnection.setConnectTimeout(15000);
                    urlConnection.setDoInput(true);// true indicates the server returns response
                    urlConnection.setDoOutput(true);// true indicates POST request

                 /* Add header */
                    if ( !headers.isEmpty())
                    {
                        for ( Map.Entry<String, String> header : headers.entrySet() )
                        {
                            urlConnection.setRequestProperty(header.getKey(), header.getValue());
                        }
                    }
                    /* Parameter */
                    if(!params.isEmpty())
                    {
                        OutputStream os = urlConnection.getOutputStream();
                        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                        writer.write(getPostDataString(params));

                        writer.flush();
                        writer.close();
                        os.close();
                    }
                    /* Request with JSON string */
                    if(strJson!=null)
                    {
                        OutputStreamWriter wr= new OutputStreamWriter(urlConnection.getOutputStream());
                        wr.write(strJson);

                    }
                    int statusCode = urlConnection.getResponseCode();

                /* 200 represents HTTP OK */
                    if ( statusCode == HttpURLConnection.HTTP_OK )
                    {
                        inputStream = new BufferedInputStream(urlConnection.getInputStream());
                        response = convertStreamToString(inputStream);
                        Log.e("Response ::", response);
                    }

                }
                catch ( Exception e )
                {
                    Log.d("Exception::", e.getLocalizedMessage());
                }

                finally
                {
                    urlConnection.disconnect();
                }
                break;
            }
        }
    }

    private static String convertStreamToString( InputStream is )
    {

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();

        String line;
        try {

            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();
    }

    private String getPostDataString( HashMap<String, String> params ) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for ( Map.Entry<String, String> entry : params.entrySet() )
        {
            if ( first )
            {
                first = false;
            }
            else
            {
                result.append("&");
            }

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}
How to Use:
 package com.httpurlconnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class MainActivity extends AppCompatActivity
{
    private static final String TAG = "Http Connection";

    private String url = "Service Url";

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new AsyncHttpTask().execute(url);
    }

    public class AsyncHttpTask extends AsyncTask<String, Void, String>
    {
        String response=null;
        @Override
        protected String doInBackground( String... params )
        {
            try
            {
                RestClient client = new RestClient(url);
//                client.AddParam("service", "analytics");
                client.AddHeader("Content-Type", "application/json");
                try
                {
                    client.Execute(RestClient.RequestMethod.GET);
                    response = client.getResponse();
                }
                catch ( Exception e )
                {
                    e.printStackTrace();
                }
            }
            catch ( Exception e )
            {
                Log.d(TAG, e.getLocalizedMessage());
            }
            return response;
        }


        @Override
        protected void onPostExecute( String result )
        {
            /* Download complete. Lets update UI */
            if ( result!=null && result.length()>0)
            {
                Log.e("Response ====",result);
            }
            else
            {
                Log.e(TAG, "Failed to fetch data!");
            }
        }
    }

}
 
I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)