RestTemplate远程服务调用工具类封装,后期使用 可直接用
需注入RestTemplate
包是 import org.springframework.web.client.RestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class HttpRequestUtils {
private final static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);
/**
* 发送GET请求,无headers
*/
public static String get(RestTemplate restTemplate, String url) {
return exchange(restTemplate, url, HttpMethod.GET, null, "", MediaType.APPLICATION_FORM_URLENCODED);
}
/**
* 发送GET请求,有headers
*/
public static String get(RestTemplate restTemplate, String url, HashMap<String, String> headersMap) {
return exchange(restTemplate, url, HttpMethod.GET, headersMap, "", null);
}
public static String delete(RestTemplate restTemplate, String url) {
return exchange(restTemplate, url, HttpMethod.DELETE, null, "", MediaType.APPLICATION_FORM_URLENCODED);
}
/**
* 发送参数为FormData格式的Post请求
*
* @param restTemplate
* @param url
* @param headersMap
* @param formParams
* @return
*/
public static String postByForm(RestTemplate restTemplate, String url, HashMap<String, String> headersMap, MultiValueMap<String, String> formParams) {
return exchange(restTemplate, url, HttpMethod.POST, headersMap, formParams, MediaType.APPLICATION_FORM_URLENCODED);
}
/**
* 发送参数为JSON格式的Post请求
*
* @param restTemplate
* @param url
* @param headersMap
* @param jsonParams
* @return
*/
public static String postByJson(RestTemplate restTemplate, String url, HashMap<String, String> headersMap, String jsonParams) {
return exchange(restTemplate, url, HttpMethod.POST, headersMap, jsonParams, MediaType.APPLICATION_JSON);
}
public static String putByJson(RestTemplate restTemplate, String url, HashMap<String, String> headersMap, String jsonParams) {
return exchange(restTemplate, url, HttpMethod.PUT, headersMap, jsonParams, MediaType.APPLICATION_JSON);
}
private static <T> String exchange(RestTemplate restTemplate, String url, HttpMethod method, HashMap<String, String> headersMap, T params, MediaType mediaType) {
if (restTemplate == null) {
restTemplate = new RestTemplate();
}
HttpHeaders headers = new HttpHeaders();
if (headersMap != null && headersMap.size() > 0) {
Set<Map.Entry<String, String>> entries = headersMap.entrySet();
for (Map.Entry<String, String> entry : entries) {
headers.add(entry.getKey(), entry.getValue());
}
}
if (mediaType != null) {
headers.setContentType(mediaType);
}
HttpEntity<T> entity = new HttpEntity<>(params, headers);
logger.info("发送请求:" + url);
logger.info("参数:" + params);
ResponseEntity<String> responseResult = restTemplate.exchange(url, method, entity, String.class);
logger.info("执行结果:" + responseResult);
return responseResult.getBody();
}
//拼装请求路径
public static String getHttpUrl(String networkProtocol, String ip, Integer port, String suffix) {
return networkProtocol + ip + ":" + port + suffix;
}
//拼装请求路径
public static String getHttpUrl(String networkProtocol, String ip, String port, String suffix) {
return networkProtocol + ip + ":" + port + suffix;
}
}
调用使用 简单举例 记录
注入restTemplate
@Autowired private RestTemplate restTemplate;
1. 发送GET请求,无headers
String httpUrl = HttpRequestUtils.getHttpUrl("http", "127.0.0.1", 9010, "/tree/test"); String body = HttpRequestUtils.get(restTemplate, httpUrl); return JSONObject.parseObject(body, Result.class);
2.发送GET请求,有headers
String httpUrl = HttpRequestUtils.getHttpUrl("http", "127.0.0.1", 9001, "/resourcesApproval/getReviewersByApprovalType"); httpUrl = httpUrl + String.format("?approvalType=%s&userId=%s", approvalType, userId); HashMap<String, String> headersMap = new HashMap<>(); headersMap.put("token", getCookie()); String body = HttpRequestUtils.get(restTemplate, httpUrl, headersMap); JSONObject actResult = JSONObject.parseObject(body); Integer code = actResult.getInteger("code"); if (500 == code) { String message = actResult.getString("message"); throw new RestfulException(Result.ERROR, "获取审批人失败:" + message); } String data = actResult.getString("data"); List<User4> Users = JSONArray.parseArray(data, User4.class);
3.发送参数为FormData格式的Post请求
String httpUrl = HttpRequestUtils.getHttpUrl("http", "127.0.0.1", 9010, "/storageConfig/createTest"); MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("projectTeamId", 参数1); params.add("projectTeamName", 参数2); String body = HttpRequestUtils.postByForm(restTemplate, httpUrl, null, params); JSONObject content1 = JSONObject.parseObject(body);
4.发送参数为JSON格式的Post请求
String httpUrl = HttpRequestUtils.getHttpUrl("http", "127.0.0.1", 9010, "/ar/getAchlistPage");
String body = HttpRequestUtils.postByJson(restTemplate, httpUrl, null, JSONObject.toJSONString(分页实体参数));
return JSONObject.parseObject(body, Result.class);