【问题标题】:Logging with Retrofit2 without OkHttp intercept使用没有 OkHttp 拦截的 Retrofit2 进行日志记录
【发布时间】:2016-12-22 07:09:57
【问题描述】:

我想在不使用 okHttp 库的情况下记录retrofit2 请求的完整请求(url、请求参数、正文)。怎么办呢

【问题讨论】:

    标签: android retrofit2


    【解决方案1】:

    你必须添加日志拦截器:

    编译'com.squareup.okhttp3:logging-interceptor:3.4.1'
    编译 '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();
    

    没有捷径,你不能在没有 okhttp 的情况下使用改造,从 4.4 开始,Android 上的 HttpUrlConnection 无论如何都使用 OkHttp: https://github.com/google/agera/issues/22

    【讨论】:

      【解决方案2】:

      我做的一个简单的类 优势

      1. 调用api的通用类
      2. 内置的进度条处理程序无需显示或关闭
      3. 使用格式登录您自己的记录器
      4. 内置多部分,即

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

      改造通用类

      /*
       * 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);
      }
      

      如何使用(用于 Post 方法)

      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);
                          }
                      });
      

      【讨论】:

      • 在日志打印中记录:D
      • 为什么要downwote?,对不起没有得到你:(
      猜你喜欢
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 2023-02-09
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多