RestTemplate真实案例

1. 场景描述

现在越来越的系统之间的交互采用http+json的交互方式,以前用的比较多的HttpClient,后来用的RestTemplate,感觉RestTemplate要比httpClent简洁的多,简单介绍下,项目中正在使用的get和post调用方式。

2. 解决方案

2.1 简要说明

RestTemplate是集成在spring-web中的,因为springboot的starter已经默认加载进来,所以可以直接使用不用再配置maven的gav了。

2.2 post调用方式

2.2.1 真实代码
    public static String invoke(String url, HashMap params) throws Exception {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/json; charset=UTF-8"));
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> httpEntity = new HttpEntity<>(JSONObject.toJSONString(params), headers);
        
        RestTemplate rst = new RestTemplate();
        ResponseEntity<String> stringResponseEntity = rst.postForEntity(url, httpEntity, String.class);

        return stringResponseEntity.getBody();
    }
2.2.2 代码说明

invoke是通用方法调用,项目中的入参是:url和map,url是调用地址,写在配置文件中;map是外围系统需要的参数,在相关类中进行封装后传过来。

2.3 get调用方式

2.3.1真实代码
	public JSONArray getUsers() throws Exception {
		JSONArray result = new JSONArray();
		try {
			RestTemplate restTemplate = new RestTemplate();
			result = restTemplate.getForObject(apiUrl + "/user/list?appCode={1}",
					JSONArray.class, code);
		} catch (Exception e) {
		}
		return result;
	}
2.3.2 代码说明

其中参数是:url和code,根据code去查询对应集合。

2.4 RestTemplate Api说明

DELETE delete
GET getForObject
getForEntity
HEAD headForHeaders
OPTIONS optionsForAllow
POST postForLocation
postForObject
postForEntity
PUT put
any exchange
execute

一般只需记住get与post的五个就可以了(getForObject 、getForEntity、postForLocation、postForObjec、postForEntity),这几个方法有很多重载的方法,参数不一样,可根据实际情况调用。


原文地址:https://www.cnblogs.com/ruanjianlaowang/p/11182682.html