Explanation of Retrofit 2.0 Common Parameters (Fixed Parameters)

  • 2021-08-31 09:00:13
  • OfStack

This article mainly introduces the common parameters (fixed parameters) of Retrofit2.0 and shares them with you as follows:

Please read first:
Retrofit dynamic parameters (non-fixed parameters, non-required parameters) (Get, Post requests)

In the actual project, for the network request that needs to be added with public parameters, the following code can be used to realize it:


RestAdapter restAdapter = new RestAdapter.Builder()
    .setEndpoint(ctx).setRequestInterceptor(new RequestInterceptor() {
     @Override
     public void intercept(RequestFacade request) {
      request.addQueryParam("publicParams", "1");
     }
    }).setConverter(new BaseConverter())
    .build();

When instantiating the object of RestAdapter, you can specify an implementation class of RequestInterceptor interface. In this class, you can set the relevant parameters of the request body, such as addHeader, addQueryParam, etc.

Unfortunately, Retrofit 2.0 has no such class. What should I do? It is implemented through Interceptor.

Interceptor is an interceptor that adds 1 parameter or gets 1 information before sending.


/**
 *  Encapsulate common parameters ( Key And passwords) 
 * <p>
 */
public class CommonInterceptor implements Interceptor {
 private final String mApiKey;
 private final String mApiSecret;

 public CommonInterceptor(String apiKey, String apiSecret) {
  mApiKey = apiKey;
  mApiSecret = apiSecret;
 }

 @Override public Response intercept(Interceptor.Chain chain) throws IOException {
  String marvelHash = ApiUtils.generateMarvelHash(mApiKey, mApiSecret);
  Request oldRequest = chain.request();

  //  Add a new parameter 
  HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
    .newBuilder()
    .scheme(oldRequest.url().scheme())
    .host(oldRequest.url().host())
    .addQueryParameter(MarvelService.PARAM_API_KEY, mApiKey)
    .addQueryParameter(MarvelService.PARAM_TIMESTAMP, ApiUtils.getUnixTimeStamp())
    .addQueryParameter(MarvelService.PARAM_HASH, marvelHash);

  //  A new request 
  Request newRequest = oldRequest.newBuilder()
    .method(oldRequest.method(), oldRequest.body())
    .url(authorizedUrlBuilder.build())
    .build();

  return chain.proceed(newRequest);
 }
}

Okhttp3 uses decorator mode, adding Interceptor using Builder.


CommonInterceptor commonInterceptor = new CommonInterceptor(
    "key", "Secret");

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

//  Adapter 
Retrofit retrofit = new Retrofit.Builder()
  .baseUrl("url")    
  .addConverterFactory(GsonConverterFactory.create()
  .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
  .client(client)
  .build();

Sometimes if you find a line, you can find more along the line.

Background

In the development of Android Http API requests, it is often encountered that each request should take one or more fixed parameters, such as:

Device only 1 ID: device_id = 7a4391e28f309c21 Service only 1 ID: uid = 2231001 Platform type: platform = android Client version number: version_code = 6 …

These parameters are required every time a request occurs, so let's call them public parameters (or basic parameters). Common Parameter 1 typically inserts requests in the form of header line, url query, or post body (less).

Realization

If you use OkHttp as http request client, this becomes much simpler. OkHttp provides a powerful interceptor component (Interceptor):

Interceptors are a powerful mechanism that can monitor, rewrite, and retry calls.

In other words, one of the interceptor functions of OkHttp is to intercept, modify and then issue the request that will be issued. This is exactly what we want. BasicParamsInterceptor implements the okhttp3. Interceptor interface.

A method for implement public Response intercept (Chain chain) throws IOException. Using Builder mode, expose the following interfaces:


addParam(String key, String value)

post request, and when body type is x-www-form-urlencoded, the key-value pair common parameter is inserted into the body parameter, and other cases are inserted into the url query parameter.


addParamsMap(Map paramsMap)

Same as above, but here the key-value pair Map is used as a parameter for batch insertion.


addHeaderParam(String key, String value)

Insert key-value pair parameters in header.


addHeaderParamsMap(Map headerParamsMap)

Insert the key-value pair Map set in header, and insert it in batches.


addHeaderLine(String headerLine)

Insert an headerLine string in header, and the string must match-1! = headerLine. indexOf (":"), which resolves to key-value pairs.


addHeaderLinesList(List headerLinesList)

Same as above, headerLineList: List is a parameter, and headerLine is inserted in batches.


addQueryParam(String key, String value)

Insert key-value pair parameters into url query.


/**
 *  Encapsulate common parameters ( Key And passwords) 
 * <p>
 */
public class CommonInterceptor implements Interceptor {
 private final String mApiKey;
 private final String mApiSecret;

 public CommonInterceptor(String apiKey, String apiSecret) {
  mApiKey = apiKey;
  mApiSecret = apiSecret;
 }

 @Override public Response intercept(Interceptor.Chain chain) throws IOException {
  String marvelHash = ApiUtils.generateMarvelHash(mApiKey, mApiSecret);
  Request oldRequest = chain.request();

  //  Add a new parameter 
  HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
    .newBuilder()
    .scheme(oldRequest.url().scheme())
    .host(oldRequest.url().host())
    .addQueryParameter(MarvelService.PARAM_API_KEY, mApiKey)
    .addQueryParameter(MarvelService.PARAM_TIMESTAMP, ApiUtils.getUnixTimeStamp())
    .addQueryParameter(MarvelService.PARAM_HASH, marvelHash);

  //  A new request 
  Request newRequest = oldRequest.newBuilder()
    .method(oldRequest.method(), oldRequest.body())
    .url(authorizedUrlBuilder.build())
    .build();

  return chain.proceed(newRequest);
 }
}
0

Insert key value pair parameter map into url query, batch insert.

Example

Create an Interceptor object using the Buider schema, and then call the addInterceptor (Interceptor i) method of OkHttp to add the interceptor object to client:


/**
 *  Encapsulate common parameters ( Key And passwords) 
 * <p>
 */
public class CommonInterceptor implements Interceptor {
 private final String mApiKey;
 private final String mApiSecret;

 public CommonInterceptor(String apiKey, String apiSecret) {
  mApiKey = apiKey;
  mApiSecret = apiSecret;
 }

 @Override public Response intercept(Interceptor.Chain chain) throws IOException {
  String marvelHash = ApiUtils.generateMarvelHash(mApiKey, mApiSecret);
  Request oldRequest = chain.request();

  //  Add a new parameter 
  HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
    .newBuilder()
    .scheme(oldRequest.url().scheme())
    .host(oldRequest.url().host())
    .addQueryParameter(MarvelService.PARAM_API_KEY, mApiKey)
    .addQueryParameter(MarvelService.PARAM_TIMESTAMP, ApiUtils.getUnixTimeStamp())
    .addQueryParameter(MarvelService.PARAM_HASH, marvelHash);

  //  A new request 
  Request newRequest = oldRequest.newBuilder()
    .method(oldRequest.method(), oldRequest.body())
    .url(authorizedUrlBuilder.build())
    .build();

  return chain.proceed(newRequest);
 }
}
1

TODO

Support for automatic timestamp common parameters Support for dynamic parameters (for example, insert uid returned by server after login)

Source code

Source and reference: https://github.com/jkyeo/okhttp-basicparamsinterceptor

basicparamsinterceptor application

Configure basic commit parameters

We can build an interceptor. Here I add some simple system parameters, as follows:


/**
 *  Encapsulate common parameters ( Key And passwords) 
 * <p>
 */
public class CommonInterceptor implements Interceptor {
 private final String mApiKey;
 private final String mApiSecret;

 public CommonInterceptor(String apiKey, String apiSecret) {
  mApiKey = apiKey;
  mApiSecret = apiSecret;
 }

 @Override public Response intercept(Interceptor.Chain chain) throws IOException {
  String marvelHash = ApiUtils.generateMarvelHash(mApiKey, mApiSecret);
  Request oldRequest = chain.request();

  //  Add a new parameter 
  HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
    .newBuilder()
    .scheme(oldRequest.url().scheme())
    .host(oldRequest.url().host())
    .addQueryParameter(MarvelService.PARAM_API_KEY, mApiKey)
    .addQueryParameter(MarvelService.PARAM_TIMESTAMP, ApiUtils.getUnixTimeStamp())
    .addQueryParameter(MarvelService.PARAM_HASH, marvelHash);

  //  A new request 
  Request newRequest = oldRequest.newBuilder()
    .method(oldRequest.method(), oldRequest.body())
    .url(authorizedUrlBuilder.build())
    .build();

  return chain.proceed(newRequest);
 }
}
2

The above Utils class is the tool class used in okio. Buffer. Build 1 basic common parameters to upload through RequestBody, and then pass " & "Symbol in body of http, other parameters to be submitted are spliced. Then recreate request object through requestBuilder, and then return Response through chain. proceed (request).

Next, when creating the OkHttpClient object, it is modified to the following code:


mOkHttpClient = new OkHttpClient.Builder()
  .addInterceptor(interceptor)
  .addInterceptor(new HttpBaseParamsLoggingInterceptor())
  .build();

In this way, 1 basic public parameters are added.

The following is implemented with BasicParamsInterceptor, and the code is as follows:


/**
 *  Encapsulate common parameters ( Key And passwords) 
 * <p>
 */
public class CommonInterceptor implements Interceptor {
 private final String mApiKey;
 private final String mApiSecret;

 public CommonInterceptor(String apiKey, String apiSecret) {
  mApiKey = apiKey;
  mApiSecret = apiSecret;
 }

 @Override public Response intercept(Interceptor.Chain chain) throws IOException {
  String marvelHash = ApiUtils.generateMarvelHash(mApiKey, mApiSecret);
  Request oldRequest = chain.request();

  //  Add a new parameter 
  HttpUrl.Builder authorizedUrlBuilder = oldRequest.url()
    .newBuilder()
    .scheme(oldRequest.url().scheme())
    .host(oldRequest.url().host())
    .addQueryParameter(MarvelService.PARAM_API_KEY, mApiKey)
    .addQueryParameter(MarvelService.PARAM_TIMESTAMP, ApiUtils.getUnixTimeStamp())
    .addQueryParameter(MarvelService.PARAM_HASH, marvelHash);

  //  A new request 
  Request newRequest = oldRequest.newBuilder()
    .method(oldRequest.method(), oldRequest.body())
    .url(authorizedUrlBuilder.build())
    .build();

  return chain.proceed(newRequest);
 }
}
4

Just configure it like the above 1.


Related articles: