spring RestTemplate提交json格式数据

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

 

接收:

    @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注解获取请求体参数

 

请求:

    @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; }
 
posted @ 2020-01-11 12:20  护花使者  Views(5742)  Comments(0Edit  收藏  举报