我试图为我的所有请求设置一个给定的标题字段(" Content-Type:text / xml; charset = utf-8")。
现在,我在我的Retrofit界面中指定了这个,在每个调用之上,如下所示:
@Headers("Content-Type: text/xml; charset=utf-8")
@POST("./")
Call<...> method(@Header("MyAction") String header, @Body ... envelop);
它有效,但由于我的所有请求共享相同的Content-Type,我只想指定一次。 从Retrofit's doc可以使用这样的拦截器来实现:
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("User-Agent", "Your-App-Name")
.header("Accept", "application/vnd.yourapi.v1.full+json")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
}
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
这对我不起作用。根据http3 Logging Interceptor,我的标题值设置为&#34; Content-Type: application / xml; charset = utf-8&#34;,我不知道为什么会有这个价值。
我遇到过很多遇到这个问题的话题,但我还没有找到令人满意的答案。
如何指定此标题字段一次?这是Retrofit中的错误吗?有没有解决方法?
由于
答案 0 :(得分:0)
我的标题有类似的问题。在我的情况下,我有两个拦截器:
我这样设置:
OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.addInterceptor { chain ->
/* edit headers */
return chain.proceed(builder.build())
}
.build()
它没有用。要解决这个问题,我只需要切换设置方法(听起来很奇怪,但它有所帮助):
OkHttpClient.Builder()
.addInterceptor { chain ->
/* edit headers */
return chain.proceed(builder.build())
}
.addInterceptor(loggingInterceptor)
.build()
你可以尝试这个技巧,希望它会有所帮助。