RestTemplate的post请求json格式问题

1. 返回格式不正确,发现问题

    由于缺少经验,传入一个body,但是在return时不是json格式,导致无法响应的问题,如下:

public GlobalMessage test(TestBody body){
    return restTemplate.postForEntity("http://testDemo/test",  body,

 GlobalMessage.class).getBody();}


       了解到所存在的问题之后,感觉这个错误太低级,实在没什么好说的,于是想将其转为json格式,入参仍是body。
       使用的是RestTemplate类中的postForEntity方法,关于RestTemplate类的几种请求方式,在上一博文中已进行相关的介绍,此处不再赘述。

2. 转换为json格式返回

       关于本项目中的body的几点说明:
       body中有五个参数,分别是:String类型的id,testId和testTake,body类型的data和user。
将1中的代码进行修改,如下:

public GlobalMessage test(TestBody body){
    HttpHeaders headers = new HttpHeaders();
    MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
    headers.setContentType(type);
    headers.add("Accept", MediaType.APPLICATION_JSON.toString());
    JSONObject jsonObj = new JSONObject();
    jsonObj.put("id", body.getId());
    jsonObj.put("data", body.getData());
    jsonObj.put("testId", body.getTestId());
    jsonObj.put("user", body.getUser());
    jsonObj.put("testtake", body.getTestTake());
    HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
    return restTemplate.postForEntity("http://testDemo/test",formEntity,
            GlobalMessage.class).getBody();
}
       其中用到了setContentType()方法和JSONObject类,这是比较关键的点,希望大家有相似情况的要多注意一些。

版权声明:本文为MrRightMeng原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。