zoukankan      html  css  js  c++  java
  • 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; }
     
  • 相关阅读:
    常见的HTTP状态码(HTTP Status Code)说明
    eclipse tomcat maven热部署
    log4j.properties 详解与配置步骤
    js玩命加载……
    git学习
    vim学习笔记
    Android中在不同activity中进行自定义广播的解析
    Android中本地广播的实现
    Android中自定义广播的实现
    Android中获得网络状况的实现
  • 原文地址:https://www.cnblogs.com/chenmz1995/p/12179551.html
Copyright © 2011-2022 走看看