Logging with Retrofit2 without OkHttp intercept

1.1k Views Asked by At

I want to log the complete request (url, request param, body) of retrofit2 request without using okHttp Library. How can it be done

2

There are 2 best solutions below

0
On BEST ANSWER

You have to add logging-interceptor:

compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.squareup.retrofit2:retrofit:2.1.0'

OkHttpClient.Builder builder = new OkHttpClient.Builder();
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
                httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                builder.networkInterceptors().add(httpLoggingInterceptor);

OkHttpClient client = new OkHttpClient.Builder()
                        .addInterceptor(httpLoggingInterceptor).build();

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

there are no shortcuts, you can not use retrofit without okhttp, As of 4.4, HttpUrlConnection on Android uses OkHttp under the hood anyway: https://github.com/google/agera/issues/22

2
On

A Simple class made by me Advantage

  1. Common class to call api
  2. Progressbar handler in built no need to show or dismiss
  3. Log in your own logger with format
  4. Multipart inbuilt i.e.

    HashMap<String, File> fileParams = new HashMap<>(); if (selectedImage != null) fileParams.put("image", new File(selectedImage)); Retrofit.getInstance("user/editprofile", params, fileParams)

Retrofit common class

/*
 * Created by RajeshKushvaha on 19-10-16
 */

public abstract class Retrofit implements Callback<ResponseBody> {
private static final String BASE_URL = "http://192.168.1.100/apps/demo/web/v1/"; //Local

private ProgressDialog progress;

public Retrofit() {
}

public Retrofit(Context context) {
    if (progress != null && progress.isShowing()) {
        progress.dismiss();
    }
    progress = new ProgressDialog(context, R.style.ProgressDialog);
    progress.setIndeterminate(true);
    progress.setIndeterminateDrawable(context.getResources().getDrawable(R.drawable.shape_drawable_progress));
    progress.setCancelable(false);
    progress.setCanceledOnTouchOutside(false);
    progress.show();
}

public Retrofit(Context context, boolean isLoadMore) {
    if (isLoadMore) return;
    if (progress != null && progress.isShowing()) {
        progress.dismiss();
    }
    progress = new ProgressDialog(context, R.style.ProgressDialog);
    progress.setIndeterminate(true);
    progress.setIndeterminateDrawable(context.getResources().getDrawable(R.drawable.shape_drawable_progress));
    progress.setCancelable(false);
    progress.setCanceledOnTouchOutside(false);
    progress.show();
}

public static Call<ResponseBody> getInstance(String endPoint,
                                             HashMap<String, String> params) {
    return getInstance(endPoint, params, null);
}

public static Call<ResponseBody> getInstance(String endPoint,
                                             HashMap<String, String> params,
                                             HashMap<String, File> files) {
    HashMap<String, RequestBody> bodyParams = null;

    Logger.e("URL", BASE_URL + endPoint);
    if (files != null && files.size() > 0) {
        bodyParams = new HashMap<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            Logger.e("params", entry.getKey() + "\t" + entry.getValue());
            bodyParams.put(entry.getKey(), createPartFromString(entry.getValue()));
        }
        for (Map.Entry<String, File> entry : files.entrySet()) {
            Logger.e("params", entry.getKey() + "\t" + entry.getValue().getPath());
            String fileName = entry.getKey() + "\"; filename=\"" + entry.getValue().getName();
            bodyParams.put(fileName, createPartFromFile(entry.getValue()));
        }
    } else {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            Logger.e("params", entry.getKey() + "\t" + entry.getValue());
        }
    }

    //Added for handle timout you can skip this
    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .build();

    ApiInterface apiInterface = new retrofit2.Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .build().create(Retrofit.ApiInterface.class);

    return bodyParams != null ? apiInterface.methodMultipart(endPoint, bodyParams) : apiInterface.method(endPoint, params);
}

@Override
public void onResponse(Call call, Response response) {
    if (progress != null && progress.isShowing()) progress.dismiss();
    String body = null;
    try {//Converting string to JSONObject
        if (response.body() != null) {
            body = ((ResponseBody) response.body()).string();
            JSONObject object = new JSONObject(body);
            Logger.e("Response", call.request().url().toString() + "\n" + object.toString());
            onResponse(response.code(), object);
        } else {
            body = response.errorBody().string();
            JSONObject object = new JSONObject(body);
            Logger.e("Response", call.request().url().toString() + "\n" + object.toString());
            onFailed(response.code(), object.optString("message"));
        }
    } catch (JSONException | IOException e) {
        e.printStackTrace();
        if (body != null) Logger.e(body);
        onFailed(response.code(), "Something went wrong!\n Please try again");
    }
}

@Override
public void onFailure(Call call, Throwable t) {
    Logger.e("Response", call.request().url().toString() + "\n" + t.toString());
    if (progress != null && progress.isShowing()) progress.dismiss();
    if (t instanceof ConnectException || t instanceof SocketTimeoutException || t instanceof UnknownHostException) {
        onFailed(0, "Failed to connect with server!");
    } else if (t instanceof IOException) {
        onFailed(0, "No internet connection!");
    } else if (t instanceof RequestException) {
        onFailed(0, "Request timeout!");
    } else {
        onFailed(0, t.getMessage());
    }
}

public interface ApiInterface {

    @FormUrlEncoded
    @POST
    Call<ResponseBody> method(@Url String endpoint,
                              @FieldMap HashMap<String, String> fields);

    @Multipart
    @POST
    Call<ResponseBody> methodMultipart(@Url String endpoint,
                                       @PartMap HashMap<String, RequestBody> fields);
}

private static RequestBody createPartFromString(String value) {
    return RequestBody.create(MediaType.parse("multipart/form-data"), value);
}

private static RequestBody createPartFromFile(File file) {
    return RequestBody.create(MediaType.parse("multipart/form-data"), file);
}

public abstract void onResponse(int statusCode, JSONObject jResponse);

public abstract void onFailed(int statusCode, String message);
}

How to use (for Post method)

HashMap<String, String> params = new HashMap<>();
        params.put("email", email);
        params.put("password", password);

        Retrofit.getInstance("user/login", params)//user/login was endpoint
                .enqueue(new Retrofit(ForgetPasswordActivity.this/*pass context if you want progressbar*/) {
                    @Override
                    public void onResponse(int statusCode, JSONObject jResponse) {
                        //handle your response
                    }

                    @Override
                    public void onFailed(int statusCode, String message) {
                        showToast(message);
                    }
                });