要在每个方法上注释@Headers("Content-Type: application/json"),太麻烦。用拦截器+反射,上代码:
public class RetrofitUtil {
public static OkHttpClient genericClient() {
OkHttpClient httpClient = new OkHttpClient();
httpClient.interceptors().add(chain -> {
Request request = chain.request();
MediaType mediaType = request.body().contentType();
try {
Field field = mediaType.getClass().getDeclaredField("mediaType");
field.setAccessible(true);
field.set(mediaType, "application/json");
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return chain.proceed(request);
});
return httpClient;
}
}
调用的时候这么写:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Http.URL)
.addConverterFactory(GsonConverterFactory.create())
.client(RetrofitUtil.genericClient())
.build();