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

调用Google API时遇Invalid JSON payload错误请求排查

问题诊断

你遇到的核心问题是请求体的实体类型与Content-Type不匹配:
虽然你手动设置了Content-Type为application/x-www-form-urlencoded,但使用Entity.text(body)发送请求时,JAX-RS客户端会将请求体标记为text/plain类型,覆盖了你手动设置的Header,导致Google OAuth服务器无法正确解析表单格式的请求,误将其当作JSON处理,从而抛出Invalid JSON payload received错误。

解决方案

有两种修复方式,推荐使用第一种更规范的实现:

方式1:使用表单实体类构建请求(推荐)

用MultivaluedMap存储表单参数,通过Entity.form()生成正确的请求实体,JAX-RS会自动处理Content-Type和参数编码:

public Response getGoogleAuth(@QueryParam("state") String state,
        @QueryParam("code") String code,
        @QueryParam("scope") String scope) {
    try {
        MultivaluedMap<String, String> formData = new MultivaluedHashMap<>();
        formData.add("code", code);
        formData.add("client_id", {googleClientId});
        formData.add("client_secret", {googleClientSecret});
        formData.add("redirect_uri", {url});
        formData.add("grant_type", "authorization_code");

        webTarget = client.target("https://oauth2.googleapis.com/token");

        Response response = webTarget.request()
                .post(Entity.form(formData), Response.class);
        ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        String responseString = response.readEntity(String.class);
        
        if (responseString.contains("error")) {
            return Response.status(200).entity("Error while authenticating user: " + responseString).build();
        }
       
        return Response.status(200).entity("User authorized: ").build();
    } catch (Exception e) {
        e.printStackTrace();
        return Response.status(113).entity("Error while authorizing the user" + e.getMessage()).build();
    }
}

方式2:修正实体类型匹配

如果坚持手动拼接表单字符串,需要使用Entity.entity()指定正确的媒体类型,而不是Entity.text():

// 替换原post请求部分
Response response = webTarget.request()
        .post(Entity.entity(body, MediaType.APPLICATION_FORM_URLENCODED), Response.class);
额外说明
  • Entity.form()会自动处理参数的URL编码(比如重定向URI中的特殊字符),避免手动拼接字符串可能引发的编码错误,这也是推荐使用它的原因。
  • 确保redirect_uri与Google API控制台中配置的完全一致,包括协议(http/https)、域名和路径,任何细微差异都会导致认证失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:35:34