码迷,mamicode.com
首页 > 编程语言 > 详细

spring RestTemplate提交json格式数据

时间:2020-01-11 13:12:28      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:返回值   shm   url   sim   name   参数   method   格式   hashmap   

 RestTemplate是spring封装的,使用起来更加简单。

 

接收:

@ApiOperation(value = "restTemplate测试", notes = "restTemplate测试", httpMethod = "POST", response = BaseResult.class)
    @ApiImplicitParams({})
    @RequestMapping(value = "/restTemplateTest.do", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> restTemplateTest(HttpServletRequest request, @RequestBody Map<String, Object> params) throws Exception {
        Map<String, Object> result = getParams(request);
        try {
            System.out.println(params);
            result.put("isLog", false);
            result.put("success", true);
            result.put("msg", "测试成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("isLog", false);
            result.put("success", false);
            result.put("msg", "测试失败:" + e.getMessage());
        }
        return result;
    }

 

这边注意可以用@RequestBody注解获取请求体参数

 

请求:

 @ApiOperation(value = "restTemplate测试", notes = "restTemplate测试", httpMethod = "POST", response = BaseResult.class)
    @ApiImplicitParams({})
    @RequestMapping(value = "/testRestTemplate.do", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> testRestTemplate(HttpServletRequest request) throws Exception {
        Map<String, Object> result = new HashMap<>();
        try {
            SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
            factory.setReadTimeout(10000);//单位为ms
            factory.setConnectTimeout(10000);//单位为ms
            RestTemplate restTemplate = new RestTemplate(factory);
            String url = "http://192.168.71.179:8080/xxxx/restTemplateTest.do";
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Content-Type", "application/json;charset=utf-8");
            Map<String, Object> map = new HashMap<>();
            map.put("name", "福州陈冠希");
            HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<Map<String, Object>>(map, requestHeaders);
//url 方法类型 请求体参数 返回值类型 ResponseEntity
<Map> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class); Map body = exchange.getBody(); System.out.println(JSON.toJSONString(body)); result.put("isLog", false); result.put("success", true); result.put("msg", "测试成功"); } catch (Exception e) { e.printStackTrace(); result.put("isLog", false); result.put("success", false); result.put("msg", "测试失败:" + e.getMessage()); } return result; }

spring RestTemplate提交json格式数据

标签:返回值   shm   url   sim   name   参数   method   格式   hashmap   

原文地址:https://www.cnblogs.com/chenmz1995/p/12179551.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!