RestTemplate传递对象或参数访问SpringMVC

最近在优化项目,将里面的交易日志插入部分分离了出来,现在就要将主系统得到的日志发送到
日志系统,来减轻主项目对数据库的压力,现将日志发送给日志系统的方案有三个,其一为
RestTemplate发送,其二为kafka,其三为PostMethod。此处仅讲解RestTemplate的具体用
法,以备后用。

服务端代码

	@RequestMapping("/json.do")
	public void myJson(@RequestParam("repo") String repo, HttpServletResponse po) throws Exception {
		System.out.println(repo);
		JSONObject jo = new JSONObject();
		jo.put("message",
				"{ringDialTime=\"1111122\", ringdialTimestamp=\"1513059248647\", establishedTimestamp=\"1513099248647\"}");
		po.getWriter().write(jo.toString());

	}

	@RequestMapping("/getEntity.do")
	public void getEntity(@RequestBody User user, HttpServletResponse po) throws Exception {
		System.out.println(user.getName());
		JSONObject jo = new JSONObject();
		jo.put("message",
				"{ringDialTime=\"1111122\", ringdialTimestamp=\"1513059248647\", establishedTimestamp=\"1513099248647\"}");
		po.getWriter().write(jo.toString());

	}
	

客户端代码

	public static void main(String[] args) throws HttpException, IOException {
		RestTemplate pp =new RestTemplate();
		User a = new User();
		a.setEmail("email");
		a.setName("ljp");
		ResponseEntity<String> postForEntity = pp.postForEntity("http://127.0.0.1:8081/SpringMVC-T/inde/getEntity.do",a,String.class);//传递实体
		ResponseEntity<String> postForEntity2 = pp.postForEntity("http://127.0.0.1:8081/SpringMVC-T/inde/json.do?repo=ljp",null,String.class);//传参
		System.out.println(postForEntity+"\n"+postForEntity2);
		System.out.println(postForEntity.getBody());
	}

我们知道,调用reseful接口传递的数据内容是json格式的字符串,返回的响应也是json格式的字符串。然而restTemplate.postForObject方法的请求参数RequestBean和返回参数ResponseBean却都是java类。是RestTemplate通过HttpMessageConverter自动帮我们做了转换的操作。

客户端接收的返回值
可以看到服务器端返回的json串,可以通过postForEntity.getBody() 获取得到{"message":"{ringDialTime=\"1111122\"}"}

链接:https://www.jianshu.com/p/c9644755dd5e

猜你喜欢

转载自blog.csdn.net/xuxie13/article/details/79209482
今日推荐