如果请求包含JSON作为请求参数,则调用外部API会导致错误请求

时间:2017-12-04 13:01:28

标签: json spring api spring-mvc resttemplate

我正在尝试使用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。

1 个答案:

答案 0 :(得分:0)

你可以这样说:

 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();
    }
    .......
    .......