• 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; }
     
  • 相关阅读:
    不做男女朋友,做蓝颜吧
    前端 让我尴尬~
    让IE6,IE7,IE8,IE9支持CSS3
    解决chrome不能显示12PX以下字号的字体问题!
    jQuery阻止冒泡和HTML默认操作
    Lazy Load, 延迟加载图片
    解秘微软雅黑
    FLV流媒体应用大攻略
    提升你设计水平的CSS3新技术
    分享下自写的HTML CSS规范
  • 原文地址:https://www.cnblogs.com/chenmz1995/p/12179551.html
Copyright © 2020-2023  润新知