如果请求包含JSON作为请求参数,请呼叫外部API会导致不良请求



我正在尝试使用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日志显示API"不能"翻译(解码)我对其编码URLEncoder.encode(paramValue, "UTF-8")

您可以这样做:

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

最新更新