Detailed explanation of Retrofit dynamic parameters (non fixed parameters non required parameters) (Get Post requests)

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

Detailed explanation of Retrofit dynamic parameters (non-fixed parameters, non-required parameters) (Get, Post requests)

Key words: Retrofit dynamic parameters, non-fixed parameters, non-necessary parameters

There are the following scenarios:

When requesting data:
1. When the user is not logged in, there is no parameter userId;;
2. Log in with the parameter userId.

The following interfaces:


@GET("index.php?r=default/homepage")
Observable<Response<Exercise>> getDataList(@Query("page") int page);

@GET("index.php?r=default/homepage")
Observable<Response<Exercise>> getDataList(@Query("page") int page, @Query("user_id") int userId);

The difference between the two interfaces lies in whether there is an "user_id" parameter.

In doing so, I always feel a little wordy, which does not reflect the superiority of Retrofit. Is there a better way? Of course there is, that is, dynamic parameters (actually very simple).

The above two interfaces are merged into one:


@GET("index.php?r=default/homepage")
Observable<Response<Exercise>> getDataList(@Query("page") int page,@Query("user_id") Integer userId);

Use

Login:


APIWrapper.getInstance().getDataList(mCurrentPage, 10);

Not logged in:


APIWrapper.getInstance().getDataList(mCurrentPage, null);

Retrofit runs the null value parameter. If one null is passed during the actual call, the system will not make any mistakes, and this parameter will be regarded as none.

You can also use Map if the parameter name is not fixed


@GET("applist/apps/detail")
Call<ResponsePojo> getDetail(@QueryMap Map<String, String> param);

Of course, it can also support the mixed use of fixed parameters and dynamic parameters


@GET("applist/apps/detail?type=detail")
Call<ResponsePojo> getDetail(@Query("appid") String appid);

Modify Header

Fixed addition of Header


@Headers("Accept-Encoding: application/json")

@GET("applist/apps/detail?type=detail")
Call<ResponsePojo> getDetail(@Query("appid") String appid);

Dynamic addition of Header


@Headers("Accept-Encoding: application/json")

@GET("applist/apps/detail?type=detail")
Call<ResponsePojo> getDetail(@Header ("Accept-Encoding") String appid);

Multiple Header


@Headers({
  "X-Foo: Bar",
  "X-Ping: Pong"
 })
@GET("applist/apps/detail?type=detail")
Call<ResponsePojo> getDetail(@Header ("Accept-Encoding") String appid);

Mixing of fixed and dynamic Header


@Headers("Accept-Encoding: application/json")

@GET("applist/apps/detail?type=detail")
Call<ResponsePojo> getDetail(@Header ("Location") String appid);

The same applies to Post requests.


Related articles: