在json中的RestTemplate帖子,getBody为null

时间:2017-06-28 06:07:08

标签: java spring resttemplate

我遇到这样的情况:我需要调用一个外部接口,它可以用第一种方式工作。但是现在,我需要使用第二种方式,遗憾的是它没有工作。

第一种方式

try {
        String url = "http://domain/service";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        List nvps = new ArrayList();
        nvps.add(new BasicNameValuePair("jsoncommond", jsoncommond));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String APIresult = "";
        if (entity != null) {
            APIresult = EntityUtils.toString(entity, "utf-8");
        }
        System.out.println("==="+ APIresult);
        EntityUtils.consume((org.apache.http.HttpEntity) entity);
        response.close();
        response.close();
        httpclient.close();
    } catch (Exception e){
        e.printStackTrace();
    }

第二种方式

RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    HttpEntity<String> entity = new HttpEntity<String>(jsoncommond,headers);

    ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST,entity,String.class);

    System.out.println("-----"+response+"\n----=-"+response.getBody());

结果如下,response.getBody()为空

**-----<200 OK,{Server=[], Content-Type=[text;html;charset=UTF-8], Transfer-Encoding=[chunked], Date=[Wed, 28 Jun 2017 05:26:22 GMT]}>
----=-null**

jsoncommond是一个像这样的json字符串:

    {
      "request": {
        "aPPID": "aa",
        "aPPKEY": "bb"
      },
      "data": {
        "address": "x",
        "city": "y",
        "country": "z"
      }
    }

为什么?请帮我!

1 个答案:

答案 0 :(得分:0)

看起来WS期望jsoncommond参数,但您将其作为正文发送。

请尝试使用以下代码。

MultiValueMap<String, Object> variables = new LinkedMultiValueMap<>();
variables.put("jsoncommond", Collections.singletonList(convertToJSON(jsoncommond)));

HttpEntity<String> entity = new HttpEntity<String>(variables, headers);
...

更新:

private String convertToJSON(Object obj) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        if (obj == null) {
            return null;
        } else if (obj instanceof String) {
            return (String) obj;
        }
        return mapper.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
        throw new SOAControllerInvocationException("Cannot serialize to JSON " + obj, e);
    }
}