spring RestTemplate提交json格式数据
Posted 护花使者
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring RestTemplate提交json格式数据相关的知识,希望对你有一定的参考价值。
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格式数据的主要内容,如果未能解决你的问题,请参考以下文章
Spring restTemplate 获取原始 json 字符串
springboot使用restTemplate post提交值 restTemplate post值
使用 Spring RestTemplate 解析 Json 文件
尝试使用 Spring Boots 的 RestTemplate 使用内容类型 [text/json]
如何使用 RestTemplate 在 Spring MVC 应用程序中访问来自(来自 Spring RESTful 服务)的巨大 JSON