【发布时间】:2021-09-01 14:05:57
【问题描述】:
我需要覆盖 OkHttp 默认设置的内容类型标头。我已经尝试了很多东西,这是我最接近它的工作。从我发现我需要使用拦截器但真的很难学习它们。我的预期行为是让我的 API POST 请求通过,但这不是因为没有正确设置内容类型并且我得到 415 Unsupported Media Type。我正在使用 ITGlue API。
public class APIHandler {
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
public class DefaultContentTypeInterceptor implements Interceptor {
public Response intercept(Interceptor.Chain chain)
throws IOException {
Request originalRequest = chain.request();
Request requestWithUserAgent = originalRequest
.newBuilder()
.header("Content-Type", "application/vnd.api+json")
.build();
return chain.proceed(requestWithUserAgent);
}
}
private final OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new DefaultContentTypeInterceptor()).build();
public void run(String input) throws Exception {
RequestBody requestBody = RequestBody.Companion.create("{\"data\": {\n" +
" \"type\": \"attachments\",\n" +
" \"attributes\": {\n" +
" \"attachment\": {\n" +
" \"content\": \""+input+"\",\n" +
" \"file_name\": \"test.png\"\n" +
" }\n" +
" }\n" +
"}\n" +
"}", JSON);
Request request = new Request.Builder()
.url("https://api.itglue.com/configurations/33880577/relationships/attachments")
.header("Content-Type", "application/vnd.api+json")
.addHeader("x-api-key", "ITG.baaa9df19a1ec7d2c9159d2c18eef763.TG9j_uj3kiDHIjZ4TMPz_IrfIBh9jLDvdEKc9UiwGNmVz6jnyYwFqrDgiA4ZaJB9")
.post(requestBody)
.build();
System.out.println(requestBody.toString());
Response response = client.newCall(request).execute();
【问题讨论】:
-
您是否尝试过注册网络拦截器? square.github.io/okhttp/interceptors/#network-interceptors