You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用OkHTTP3调用API返回415错误,请求排查解决方法

OkHTTP3调用API返回415状态码问题排查与解决

问题描述

  • Postman测试目标API端点正常:配置URL、访问令牌及JSON请求体后,返回200状态码与预期JSON响应
  • Java代码调用异常:获取OAuth访问令牌的请求正常,但调用alertModels接口返回415 HTTP状态码
  • 特殊现象:将Java生成的JSON请求体复制到Postman中执行仍可正常运行;且OkHTTP3配置的请求头与Postman完全一致

相关代码

public static void getAlertModels(OAuthToken oAuthToken, int customerId) throws IOException {

    ApiRequest apiRequest = new ApiRequest(
        new ApiRequestSearch(
            Arrays.asList("triggers", "customers"),
            Arrays.asList(
                Arrays.asList("product"),
                Arrays.asList(9)
            )
        )
    );
    
    ObjectMapper objectMapper = new ObjectMapper();

    String jsonBody = objectMapper.writeValueAsString(apiRequest);

    OkHttpClient client = new OkHttpClient().newBuilder().build();

    MediaType mediaType = MediaType.parse("application/json");

    RequestBody body = RequestBody.create(jsonBody, mediaType);

    Request request = new Request.Builder()
        .url("https://api.anonymous.tld/alertModels")
        .method("POST", body)
        .addHeader("Authorization", "Bearer " + oAuthToken.getAccessToken())
        .addHeader("Content-Type", "application/json")
        .addHeader("Accept", "application/json")
        .build()
    ;

    Response response = client.newCall(request).execute();

    System.out.println(jsonBody);
    System.out.println(response.code());
    System.out.println(response.body().string());
}

Postman配置截图

  • 请求体配置:
    Postman请求体配置
  • 请求头配置:
    Postman请求头配置

解决方法

1. 明确指定MediaType字符集

部分服务器会严格校验Content-Type的字符集参数,Postman默认会添加charset=utf-8但可能未在界面显示,修改MediaType定义:

MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

2. 修正RequestBody创建参数顺序

OkHTTP3的RequestBody.create存在重载方法,调整参数顺序避免歧义:

RequestBody body = RequestBody.create(mediaType, jsonBody);

3. 校验请求头是否重复或冲突

添加OkHTTP拦截器打印完整请求头,确认Content-Type未被重复添加:

OkHttpClient client = new OkHttpClient.Builder()
    .addInterceptor(chain -> {
        Request request = chain.request();
        request.headers().forEach((name, value) -> System.out.println(name + ": " + value));
        return chain.proceed(request);
    })
    .build();

如果发现重复的Content-Type头,改用header()方法替代addHeader()(header()会覆盖已有同名字段):

.requestBuilder.header("Content-Type", "application/json; charset=utf-8")

4. 确认JSON序列化格式一致性

打印jsonBody并与Postman中使用的原始JSON逐字符对比,确保ObjectMapper未生成额外转义字符或格式差异(比如数组嵌套、字段大小写是否完全匹配)。

内容的提问来源于stack exchange,提问作者Alexandre

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 12:40:09