Add Header Parameter in Retrofit

前端 未结 5 1045
抹茶落季
抹茶落季 2020-12-28 12:44

I\'m trying to call an API which requires me to pass in an API key.

My Service call using HttpURLConnection is working perfectly.

url = new URL(\"htt         


        
5条回答
  •  臣服心动
    2020-12-28 13:04

    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

提交回复
热议问题