SoFunction
Updated on 2025-04-10

Learn more about the Interceptors of OkHttp3

OKHttp official website introduces: Interceptors are a powerful mechanism that can monitor, rewrite and retry calls. Here we mainly encapsulate the network request header and data request of the interceptor.

Network request header interceptor

In Android applications, we usually need to obtain the IMEI value of the user's mobile phone and some other commonly used parameters. It will be very convenient if they are encapsulated into the request header.

Since it is a custom interceptor, we must first inherit the OKHttp interceptor and set this custom class to final type to prevent other classes from inheriting.

Here you need to operate in the intercept (Chain chain) method of the parent class. Get the object in the method and add the request header.

Create a BaseParam object to encapsulate the parameters of the request header.

public final class HeaderInterceptorTest implements Interceptor {

  /**
    * Request header parameters basic parameters
    */
  private static final String HEADER_BASE_PARAM = "baseParam";
  private static String BASE_PARAM;

  @Override
  public Response intercept(Chain chain) throws IOException {

     builder = ().newBuilder();

    (HEADER_BASE_PARAM, BASE_PARAM);
    return (());
  }

  public static void initBaseParam(Context context) {
    BaseParam baseParam = new BaseParam();
    String imei;
    String imsi;
    try {
      imei = (context);
    } catch (Exception e) {
      imei = null;
    }
    if (null == imei || ("")) {
      imei = (context);
      imsi = (context);
    } else {
      imei = (context);
      imsi = (context);
    }
    (imei);
    (imsi);
    ((context));
    ((context));
    (());
    (());
    BASE_PARAM = new Gson().toJson(baseParam).toString();
  }

  private static class BaseParam {
    /**
     * imei :
     * imsi :
     * mac :
     * version :
     * model :
     * brand :
     * city :
     */
    private String imei;
    private String imsi;
    private String mac;
    private String version;
    private String model;
    private String brand;
    private String city;

    public String getImei() {
      return imei;
    }

    public void setImei(String imei) {
       = imei;
    }

    public String getImsi() {
      return imsi;
    }

    public void setImsi(String imsi) {
       = imsi;
    }

    public String getMac() {
      return mac;
    }

    public void setMac(String mac) {
       = mac;
    }

    public String getVersion() {
      return version;
    }

    public void setVersion(String version) {
       = version;
    }

    public String getModel() {
      return model;
    }

    public void setModel(String model) {
       = model;
    }

    public String getBrand() {
      return brand;
    }

    public void setBrand(String brand) {
       = brand;
    }

    public String getCity() {
      return city;
    }

    public void setCity(String city) {
       = city;
    }
  }
}

Data request interceptor

When making data requests, a fixed request format is generally defined. Here we directly define this fixed format through the interceptor, so that it can be managed uniformly when used. The specific usage method is actually the same as above.

The main thing to note is to first get the request body set during the request, and then allow the requested data to be encapsulated into the request format set by the backend.

public class HttpDataPackInterceptorTest implements Interceptor {

  @Override
  public Response intercept(Chain chain) throws IOException {
    Request request = ();

     requestBuilder = ().newBuilder();
    //Request data processing    if (().toString().contains("uploads")) {
      //The parameters of special interfaces do not need to be processed    } else {
      //The request parameters need to be processed      if (() instanceof FormBody) {
         newFormBody = new ();
        //The request body set when obtaining the request        FormBody oldFormBody = (FormBody) ();
        Buffer buffer = new Buffer();
        (buffer);
        String postParams = ((("UTF-8")));
        String data = (postParams, "UTF-8");
        if ((data)) {
          ("data", "");
        } else {
          //Encapsulate the requested data          ("data", data);
        }
        ((), ());
      }
    }
    return (());
  }
}

Called in code

When creating the OkHttpClient object, call the addInterceptor() method to add two interceptors.

private OkHttpClient client;
  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_okhttp);
    (this);
    client= new OkHttpClient()
        .newBuilder()
        .addInterceptor(new HeaderInterceptorTest())
        .addInterceptor(new HttpDataPackInterceptorTest())
        .connectTimeout(60, )
        .writeTimeout(60, )
        .readTimeout(60, ).build();
    okhttpAsyncPost();
  }

  private void okhttpAsyncPost(){
    RequestBody formBody = new ()
        .add("page", "1")
        .add("count", "2")
        .add("type","video")
        .build();
    Request request = new ()
        .url("/getJoke")
        .post(formBody)
        .build();

    (request).enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {

      }

      @Override
      public void onResponse(Call call, Response response) throws IOException {
        ("error","result"+().string());
        ("error","method"+().toString());
        ("error","Request header"+().headers().toString());
      }
    });
  }

Printed log

Results {"status":200,"msg":"OK","data":"{\"count\":\"2\",\"page\":\"1\",\"type\":\"video\"}"}
Method Request{method=POST, url=https:///list, tags={}}
Request header baseParam: {"brand":"Xiaomi","city":"\u4e1c\u4eac","imei":"9fc70b16bf169075f556e6d67be9ef1a","imsi":"9fc70b16bf169075f556e6d67be9ef1a","mac":"02:00:00:00:00:00:00:00:00","model":"Mi Note 2","version":"1.0"}

OK, the Interceptors configuration in OKHttp3 is completed. Friends, you can set up other interceptors of their own different needs to add them to the request.

Recently I have written a lot about the use of common Android controls, which are all very useful knowledge. If you feel it is useful, please give me a star, thank you.Code example

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.