【问题标题】:Calling an external API causes Bad Request if request contains JSON as a request parameter如果请求包含 JSON 作为请求参数,则调用外部 API 会导致错误请求
【发布时间】:2017-12-04 13:01:28
【问题描述】:

我正在尝试使用 RestTemplate 将外部 API 集成到我的 Spring MVC 应用程序中。

除非我不必将 JSON 作为请求参数传递给 API 调用,否则它工作得非常好。这样的尝试每次都会导致400 Bad Request,据我在API日志中检查,我的JSON参数没有被API解码(它仍然看起来像编码的字符串)。

我认为它可能与我请求中的标头有关,但是一旦我添加了AcceptContent-Type,错误仍然相同。有人可以给我一个建议,我的实施可能有什么问题吗?

RestTemplate template = new RestTemplate();
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("Content-Type", "application/json");
body.add("Accept", "application/json");

UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromHttpUrl(url);

String encodedParamValue = URLEncoder.encode(paramValue, "UTF-8");
urlBuilder.queryParam(requestParam, encodedParamValue);

HttpEntity<?> getRequest = new HttpEntity<>(body);

String response = template.exchange(urlBuilder.build().toString(), HttpMethod.GET, getRequest, String.class).getBody();

事实 1 我很确定我的代码在连接 API 端点和请求参数后生成的 URL 是可以的,因为文档显示了相同参数的完全相同的 URL。

事实 2 如果我调用一个不需要任何参数的不同端点(只是普通端点),那么它工作正常,所以我假设我调用 API 的方式是可以的。

事实 3 就像我提到的那样,API 日志显示,一旦我将参数编码URLEncoder.encode(paramValue, "UTF-8"),API 就“无法”将参数转换(解码)为 JSON。

【问题讨论】:

    标签: json spring api spring-mvc resttemplate


    【解决方案1】:

    你可以按照这个:

     try {
            .......
            .......  
            HttpHeaders headers = new HttpHeaders();
            headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
            // Set more header params as required ....
            HttpEntity entity = new HttpEntity<>(headers);
    
            RestTemplate restTemplate = new RestTemplate();
            response = restTemplate.exchange(url, HttpMethod.GET, entity, type);
    
            if(response.getStatusCode() == HttpStatus.OK) {
                 //TODO: Need to modify response according to the demand
                if(response.getBody().getOk().equals("true") && response.getBody().getMessage() == null) {
                    response.getBody().setMessage(successMessage);
                }
    
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        .......
        .......
    

    【讨论】:

    • 与我上面的代码相比,它有什么变化?结果还是一样的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-06
    • 2020-04-16
    • 2021-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多