Retrofit 2.0.0-beta2
@Headers({
"Authorization: {authorization}",
"Content-Type: application/json"
})
@POST("/api/{id}/action/")
Call<String> postfn(@Header("Authorization") String authorization, @Path("id") String id, @Body String body);
我正在使用Gson转换器 .addConverterFactory(GsonConverterFactory.create(GSON))
我收到错误代码= 400,消息=错误请求我应该使用自定义 转换器?
请帮忙
答案 0 :(得分:2)
你不能将这两件事放在一起。
有两种方法可以使用retrofit 2.0将动态标头放在请求上
1:仅将其放在方法签名
中@Headers({
"Content-Type: application/json"
})
@POST("/api/{id}/action/")
Call<String> postfn(@Header("Authorization") String authorization, @Path("id") String id, @Body String body);
2:使用请求拦截器添加固定动态标头
public class TraktvApiProvider implements Provider<TraktvApi> {
public static final String BASE_URL = "https://api-v2launch.trakt.tv/";
@Override
public TraktvApi get() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(JacksonConverterFactory.create())
.build();
retrofit.client().interceptors().add(new LoggingInterceptor());
return retrofit.create(TraktvApi.class);
}
private class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder()
.addHeader("trakt-api-version", "2")
.addHeader("trakt-api-key", "[YOUR-API-KEY]")
.build();
Response response = chain.proceed(request);
String bodyString = response.body().string();
Log.d("Retrofit", "---------------------------------- REQUEST ----------------------------------");
Log.d("Retrofit", String.format("%s - %s", request.method(), request.url()));
Log.d("Retrofit", request.headers().toString());
Log.d("Retrofit", "---------------------------------- REQUEST ----------------------------------");
Log.d("Retrofit", "---------------------------------- RESPONSE ----------------------------------");
Log.d("Retrofit", response.headers().toString());
Log.d("Retrofit", "Body: " + bodyString);
Log.d("Retrofit", "---------------------------------- RESPONSE ----------------------------------");
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), bodyString))
.build();
}
}
}
答案 1 :(得分:0)
我回到稳定版1.9并且拦截工作正常。