2

是否可以使用 Spring RestTemplate 将原始 JSON 传递给 Rest API?

我正在尝试以下操作:

List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<HttpMessageConverter<?>>();
httpMessageConverters.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(httpMessageConverters);
String jsonText = // raw JSON
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> entity = new HttpEntity<Object>(jsonText, httpHeaders);
restTemplate.exchange(url, HttpMethod.POST, entity, responseClass);

当我调用这个请求时,我得到一个 HTTP 400 错误响应,这意味着错误的请求。但是,所有标头和 JSON 正文都与我使用 HTTP 客户端提交的相同。

相反,当我创建 MyRequest 对象并将其设置在 HttpEntity 上时,以下工作正常:

List<HttpMessageConverter<?>> httpMessageConverters = new ArrayList<HttpMessageConverter<?>>();
    httpMessageConverters.add(new MappingJacksonHttpMessageConverter());
    restTemplate.setMessageConverters(httpMessageConverters);
    MyRequest myRequest = new MyRequest();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<?> entity = new HttpEntity<Object>(myRequest, httpHeaders);
    restTemplate.exchange(url, HttpMethod.POST, entity, responseClass);

因此,我想知道如何使用字符串格式的原始 JSON 调用我的 REST API?

4

1 回答 1

1

这是方法

            String url = String.format("https://SITE");
            RestTemplate template = new RestTemplate();
            template.getMessageConverters().add(new StringHttpMessageConverter());

            String valor ="{\"cmd\":\"123\", \"includeImei\":\"true\"}";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authenticate", "TOKEN");


            HttpEntity<String> entity = new HttpEntity<String>(valor, headers);
            URI valoresdevueltos = template.postForLocation(url, entity);
于 2016-04-06T13:49:51.353 回答