首先介绍一下RestTemplate:
一、概述
- spring框架提供的RestTemplate类可用于在应用中调用rest服务,它简化了与http服务的通信方式,统一了RESTful的标准,封装了http链接, 我们只需要传入url及返回值类型即可。相较于之前常用的HttpClient,RestTemplate是一种更优雅的调用RESTful服务的方式。
- 在Spring应用程序中访问第三方REST服务与使用Spring RestTemplate类有关。RestTemplate类的设计原则与许多其他Spring *模板类(例如JdbcTemplate、JmsTemplate)相同,为执行复杂任务提供了一种具有默认行为的简化方法。
- RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),如果有需要的话也可以通过setRequestFactory方法替换为例如 Apache HttpComponents、Netty或OkHttp等其它HTTP library。
- 考虑到RestTemplate类是为调用REST服务而设计的,因此它的主要方法与REST的基础紧密相连就不足为奇了,后者是HTTP协议的方法:HEAD、GET、POST、PUT、DELETE和OPTIONS。例如,RestTemplate类具有headForHeaders()、getForObject()、postForObject()、put()和delete()等方法。
二、实现
-
最新api地址:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html
-
RestTemplate包含以下几个部分:
HttpMessageConverter 对象转换器
ClientHttpRequestFactory 默认是JDK的HttpURLConnection
ResponseErrorHandler 异常处理
ClientHttpRequestInterceptor 请求拦截器 -
常规配置
public MyRestClientService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder
.basicAuthorization("username", "password")
.setConnectTimeout(3000)
.setReadTimeout(5000)
.rootUri("http://api.example.com/")
.build();
}
然后创建HTTP工具类:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSONObject;
/**
* @description:http发送工具类
*/
public class HttpHelper {
static Logger log = LoggerFactory.getLogger(HttpHeaders.class);
/**
* 向目的URL发送post请求
* @param url 目的url
* @param json 发送的参数
* @return AdToutiaoJsonTokenData
*/
public static JSONObject sendPostRequest(String url, JSONObject json,HttpHeaders headers){
log.info(url);
RestTemplate client = new RestTemplate();
//新建Http头,add方法可以添加参数
//设置请求发送方式
HttpMethod method = HttpMethod.POST;
// 以表单的方式提交
headers.setContentType(MediaType.APPLICATION_JSON);
//将请求头部和参数合成一个请求
HttpEntity<Object> entity = new HttpEntity<Object>(json, headers);
//执行HTTP请求,将返回的结构使用String 类格式化(可设置为对应返回值格式的类)
JSONObject result = client.postForObject(url, entity, JSONObject.class);
if(!result.getString("code").equals("0"))
{
//失败再请求一次
//result = client.postForObject(url, entity, JSONObject.class);
}
return result;
}
/**
* 向目的URL发送get请求
* @param url 目的url
* @param headers 发送的http头,可在外部设置好参数后传入
* @return String
*/
public static JSONObject sendGetRequest(String url,HttpHeaders headers){
RestTemplate client = new RestTemplate();
HttpMethod method = HttpMethod.GET;
// 以表单的方式提交
headers.setContentType(MediaType.APPLICATION_JSON);
//将请求头部和参数合成一个请求
HttpEntity<Object> entity = new HttpEntity<Object>(null, headers);
ResponseEntity<JSONObject> result = client.exchange(url, method, entity, JSONObject.class);
if(!result.getBody().getString("code").equals("0"))
{
//失败再请求一次
//result = client.exchange(url, method, entity, JSONObject.class);
}
return result.getBody();
}
}
调用post方法:
public String batchAddDepartment(String AccessToken, JSONArray departments) throws Exception {
try {
HttpHeaders header = new HttpHeaders();
header.add("Authorization", "Bearer "+AccessToken);//添加header
JSONObject json = new JSONObject();
json.put("departments",departments);//添加参数
String Url = "xxx";
JSONObject jsonObj = HttpHelper.sendPostRequest(Url, json,header);
if(!jsonObj.get("code").toString().equals("0"))
{
throw new MyException(StatusCode.error_batch_add_department,jsonObj.toString(),null);
}
else
{
//return jsonObj.getJSONObject("data").get("task_id").toString();
return jsonObj.toString();
}
} catch (Exception ex) {
throw ex;
}
}
调用GET方法
/*****
* 组装url
* @param map
* @return
*/
private static String getUrlParamsByMap(Map<String, String> map) {
if (map == null) {
return "";
}
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : map.entrySet()) {
sb.append(entry.getKey() + "=" + entry.getValue());
sb.append("&");
}
String s = sb.toString();
if (s.endsWith("&")) {
s = s.substring(0, s.length() - 1);
//s = org.apache.commons.lang.StringUtils.substringBeforeLast(s, "&");
}
return s;
}
//实际service
public List<String> getChildDepartmentIdList(String AccessToken,String department_id) throws Exception{
try {
HttpHeaders header = new HttpHeaders();
header.add("Authorization", "Bearer "+AccessToken);
Map<String, String> parm = new IdentityHashMap<>();
parm.put("department_id", department_id);
String Url = "xxx"+"?"+getUrlParamsByMap(parm);
JSONObject jsonObj = HttpHelper.sendGetRequest(Url, header);
JSONArray result=new JSONArray();
if(jsonObj.getJSONObject("data").getJSONArray("departments_list") != null)
{
result = jsonObj.getJSONObject("data").getJSONArray("departments_list");
}
List<String> idList=result.toJavaList(String.class);
return idList;
} catch (Exception ex) {
throw ex;
}
}
getUrlParamsByMap可把uri组装成xxx?a=a&b=b&c=c
的字符串