Thursday, October 20, 2016

WebService Call using Retrofit with authorisation

Iin this tutorial I will explain how to call web service using retrofit with authorisation.
For that first of all in app.gradle file we will add some dependencies as below:

compile 'com.squareup.retrofit2:retrofit:2.0.0' 
compile 'com.squareup.retrofit2:converter-gson:2.0.0' 
compile 'com.github.bumptech.glide:glide:3.7.0' 
compile 'com.android.support:design:23.2.1'
 
 
Then now we will start coding as below:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private RecyclerView rvEmployees;
    private RestApi service;
    private EmployeesAdapter employeesAdapter;

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

        service = ServiceGenerator.createService(RestApi.class);
        rvEmployees = (RecyclerView) findViewById(R.id.rvEmployees);
        rvEmployees.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        rvEmployees.setItemAnimator(new DefaultItemAnimator());

        getEmployeeList();

    }

    private void getEmployeeList() {

        EmployeesReq availableDoctorsReq = new EmployeesReq();
        availableDoctorsReq.methodName = "getEmployeeList";
        availableDoctorsReq.userid = "1";

        Log.e("REQ EMP", new Gson().toJson(availableDoctorsReq));
        Call<EmployeesResp> callEmployee = service.loadEmployees(availableDoctorsReq);

        callEmployee.enqueue(new Callback<EmployeesResp>() {
            @Override            public void onResponse(Call<EmployeesResp> call, Response<EmployeesResp> response) {

                if (response.code() == 200) {
                    Log.e("RESP EMP", new Gson().toJson(response));
                    if (response.body().getData().size() > 0) {
                        employeesAdapter = new EmployeesAdapter(response.body().getData());
                        rvEmployees.setAdapter(employeesAdapter);
                    }
                }
            }

            @Override            public void onFailure(Call<EmployeesResp> call, Throwable t) {
            }
        });
    }
}


=================================================================================================
activity_main.xml

 
<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools" 
     android:layout_width="match_parent"     
     android:layout_height="match_parent" 
     android:paddingBottom="@dimen/activity_vertical_margin" 
     android:paddingLeft="@dimen/activity_horizontal_margin"     
     android:paddingRight="@dimen/activity_horizontal_margin" 
     android:paddingTop="@dimen/activity_vertical_margin"     
     tools:context="com.inx.retrofitdemo.MainActivity">


    <android.support.v7.widget.RecyclerView 
        android:id="@+id/rvEmployees"         
        android:layout_width="match_parent"         
        android:layout_height="match_parent"         
        android:scrollbars="vertical" />

</RelativeLayout>
 =================================================================================================
 
ServiceGenerator.java
 
public class ServiceGenerator {
    public static final String API_BASE_URL = "http://www.yourserver.com/";


    public static String username = "username";
    public static String password = "password";

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    public static <S> S createService(Class<S> serviceClass) {
        if (username != null && password != null) {
            String credentials = username + ":" + password;
            final String basic =
                    "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

            httpClient.addInterceptor(new Interceptor() {
                @Override                public Response intercept(Chain chain) throws IOException {
                    Request original = chain.request();

                    Request.Builder requestBuilder = original.newBuilder()
                            .header("Authorization", basic)
                            .header("Accept", "application/json")
                            .method(original.method(), original.body());

                    Request request = requestBuilder.build();
                    return chain.proceed(request);
                }
            });
        }

        OkHttpClient client = httpClient.build();
        Retrofit retrofit = builder.client(client).build();
        return retrofit.create(serviceClass);
    }
}
 
 
=================================================================================================
 
RestApi.java
 
public interface RestApi {

    @POST("webservice")
    Call<EmployeesResp> loadEmployees(@Body EmployeesReq employeesReq);

}
 
 
=================================================================================================
 
EmployeesResp.java 
 
public class EmployeesResp {


    @SerializedName("status")
    private int status;
    @SerializedName("message")
    private String message;

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

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

    @SerializedName("data")
    private List<DataEntity> data;

    public static EmployeesResp objectFromData(String str) {

        return new Gson().fromJson(str, EmployeesResp.class);
    }

    public List<DataEntity> getData() {
        return data;
    }

    public void setData(List<DataEntity> data) {
        this.data = data;
    }

    public static class DataEntity {

        @SerializedName("fu_firstname")
        private String fuFirstname;
        @SerializedName("fu_lastname")
        private String fuLastname;
        @SerializedName("fu_specialization")
        private String fuSpecialization;
        @SerializedName("fu_photo")
        private String fuPhoto;
        @SerializedName("fu_photo_thumb")
        private String fuPhotoThumb;

        public static DataEntity objectFromData(String str) {

            return new Gson().fromJson(str, DataEntity.class);
        }


        public String getFuFirstname() {
            return fuFirstname;
        }

        public void setFuFirstname(String fuFirstname) {
            this.fuFirstname = fuFirstname;
        }

        public String getFuLastname() {
            return fuLastname;
        }

        public void setFuLastname(String fuLastname) {
            this.fuLastname = fuLastname;
        }

        public String getFuSpecialization() {
            return fuSpecialization;
        }

        public void setFuSpecialization(String fuSpecialization) {
            this.fuSpecialization = fuSpecialization;
        }

        public String getFuPhoto() {
            return fuPhoto;
        }

        public void setFuPhoto(String fuPhoto) {
            this.fuPhoto = fuPhoto;
        }

        public String getFuPhotoThumb() {
            return fuPhotoThumb;
        }

        public void setFuPhotoThumb(String fuPhotoThumb) {
            this.fuPhotoThumb = fuPhotoThumb;
        }
    }
}
 
 
=================================================================================================
 
EmployeesReq.java
 
public class EmployeesReq {
    public String methodName;
    public String userid;
}
 
================================================================================================= 

row.employee.xml

 
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     
              xmlns:app="http://schemas.android.com/apk/res-auto"     
              android:layout_width="match_parent" 
              android:layout_height="60dp"     
              android:orientation="horizontal" 
              android:paddingBottom="10dp" 
              android:paddingTop="10dp">


    <ImageView
        android:id="@+id/ivEmpPic"         
        android:layout_width="50dp" 
        android:layout_height="50dp" 
        android:adjustViewBounds="true" 
        android:scaleType="centerCrop" />


    <LinearLayout         
        android:layout_width="match_parent"         
        android:layout_height="match_parent"         
        android:layout_gravity="center_vertical"         
        android:gravity="center_vertical" 
        android:orientation="vertical">

        <TextView             
           android:id="@+id/tvEmpName"             
           android:layout_width="match_parent"             
           android:layout_height="wrap_content"             
           android:layout_gravity="center_vertical" 
           android:ellipsize="end"             
           android:maxLines="1"             
           android:text="Mark Alexander" />

        <TextView 
           android:id="@+id/tvEmpPost" 
           android:layout_width="match_parent" 
           android:layout_height="wrap_content" 
           android:layout_gravity="center_vertical" 
           android:ellipsize="end"             
           android:maxLines="1" 
           android:text="General" />
 
   </LinearLayout>


</LinearLayout>

============================================================================================================
 
EmployeesAdapter.java
 
 
public class EmployeesAdapter extends RecyclerView.Adapter<EmployeesAdapter.MyViewHolder> {

    private List<EmployeesResp.DataEntity> data;

    public EmployeesAdapter(List<EmployeesResp.DataEntity> data) {
        this.data = data;

    }

    @Override    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View myView = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_employee,
                parent, false);

        return new MyViewHolder(myView);
    }

    @Override    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.tvEmpName.setText(data.get(position).getFuFirstname() + " " + data.get(position)
.getFuLastname());
        String specialization = data.get(position).getFuSpecialization();
        if (!Other.isNull(specialization)) {
            holder.tvEmpPost.setText(specialization);
        } else {
            holder.tvEmpPost.setText("-");
        }

        try {
            if (data.get(position).getFuPhoto() != null && !data.get(position)
.getFuPhoto().isEmpty()) {
                Glide
                        .with(holder.ivEmpPic.getContext())
                        .load(getGlideUrl(Other.filterString(data.get(position).getFuPhoto())))
                        .override(70, 70)
                        .centerCrop()
                        .crossFade()
                        .into(holder.ivEmpPic);
            }
        } catch (Exception e) {
            Log.e("GLIDE EXCEP", e + "");
        }
    }

    @Override    public int getItemCount() {
        return data.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tvEmpName, tvEmpPost;
        ImageView ivEmpPic;

        public MyViewHolder(View view) {
            super(view);
            tvEmpName = (TextView) view.findViewById(R.id.tvEmpName);
            tvEmpPost = (TextView) view.findViewById(R.id.tvEmpPost);
            ivEmpPic = (ImageView) view.findViewById(R.id.ivEmpPic);
        }
    }
 
public static GlideUrl getGlideUrl(String url) {
    String credentials = "username:password";
    final String basic =
            "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    return new GlideUrl(url, new LazyHeaders.Builder()
            .addHeader("Authorization", basic)
            .addHeader("Accept", "application/json")
            .build());
} 
 }


=====================================================================================