Tuesday 25 October 2016

Retrofit 2.1:

Add gradle in your app.gradle file

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

Create interface

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
public interface Api {

    @FormUrlEncoded    @POST("driver_login")
    Call<DriverLoginResponse> driverLogin(@Field("email") String email,
                                          @Field("password") String password,
                                          @Field("deviceId") String deviceId,
                                          @Field("deviceType") String deviceType);

}

Create Time class for call api:

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetroConfig {

    public static Api client() {
 
        OkHttpClient.Builder b = new OkHttpClient.Builder();
        b.readTimeout(200, TimeUnit.SECONDS);
        b.writeTimeout(600, TimeUnit.SECONDS);
        OkHttpClient client = b.build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constants.ROOT_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
        Api apiInterface = retrofit.create(Api.class);
        return apiInterface;


    }



MainActivity.class:

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

final ProgressDialog dialog = new ProgressDialog(OtpActivity.this);
dialog.setMessage("please wait...");
dialog.setCancelable(false);
dialog.show();

Call<ResponseBody> responseCall = RetroConfig.client().verifyOtp(driver_id, otp);
responseCall.enqueue(new Callback<ResponseBody>() {
    @Override    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        dialog.cancel();
        if (response.body() != null) {
            try {
                String result = response.body().string();

                JSONObject jsonObj = new JSONObject(result);

                String sres = jsonObj.getString("responce");

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override    public void onFailure(Call<ResponseBody> call, Throwable t) {
        dialog.cancel();
        Log.e("error", t.getLocalizedMessage());
    }
});



No comments:

Post a Comment