Adding header to all request with Retrofit 2

前端 未结 10 1391
北荒
北荒 2020-11-29 17:46

Retrofit 2\'s documentation says:

Headers that need to be added to every request can be specified using an OkHttp interceptor.

I

10条回答
  •  攒了一身酷
    2020-11-29 18:00

    Try this type header for Retrofit 1.9 and 2.0. For Json Content Type.

    @Headers({"Accept: application/json"})
    @POST("user/classes")
    Call addToPlaylist(@Body PlaylistParm parm);
    

    You can add many more headers i.e

    @Headers({
            "Accept: application/json",
            "User-Agent: Your-App-Name",
            "Cache-Control: max-age=640000"
        })
    

    Dynamically Add to headers:

    @POST("user/classes")
    Call addToPlaylist(@Header("Content-Type") String content_type, @Body RequestModel req);
    

    Call you method i.e

    mAPI.addToPlayList("application/json", playListParam);
    

    Or

    Want to pass everytime then Create HttpClient object with http Interceptor:

    OkHttpClient httpClient = new OkHttpClient();
            httpClient.networkInterceptors().add(new Interceptor() {
                @Override
                public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                    Request.Builder requestBuilder = chain.request().newBuilder();
                    requestBuilder.header("Content-Type", "application/json");
                    return chain.proceed(requestBuilder.build());
                }
            });
    

    Then add to retrofit object

    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(httpClient).build();
    

    UPDATE if you are using Kotlin remove the { } else it will not work

提交回复
热议问题