package com.highdatas.mdm.util; import org.springframework.http.*; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.stereotype.Component; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; import org.springframework.web.client.RestTemplate; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @author kimi * @description * @date 2019-12-13 13:35 */ @Component public class HttpUtils { public static String HttpRestClient(String url, HttpMethod method, MultiValueMap formParams) { return HttpRestClient(url,method,formParams, null, null); } public static String HttpRestClient(String url, HttpMethod method, MultiValueMap formParams, String getParams) { return HttpRestClient(url,method,formParams, getParams, null); } public static String HttpRestClient(String url, HttpMethod method, MultiValueMap formParams, MediaType mediaType) { return HttpRestClient(url,method,formParams, null, mediaType); } public static String HttpRestClient(String url, HttpMethod method, MultiValueMap formParams, String getParams, MediaType mediaType) { if (!StringUtils.isEmpty(getParams)) { url = url + Constant.QUESTION + getParams; } SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setConnectTimeout(15*1000); requestFactory.setReadTimeout(15*1000); RestTemplate client = new RestTemplate(requestFactory); client.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8)); HttpHeaders headers = new HttpHeaders(); if (mediaType == null){ headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); }else { headers.setContentType(mediaType); } HttpEntity> requestEntity = new HttpEntity>(formParams, headers); // 执行HTTP请求 ResponseEntity response = client.exchange(url, method, requestEntity, String.class); return response.getBody(); } public static String getUrlParamsByMap(Map map) { if (map == null) { return ""; } StringBuffer sb = new StringBuffer(); for (Map.Entry entry : map.entrySet()) { Object mapValue = entry.getValue(); if (mapValue instanceof List) { List valueList = (List) mapValue; mapValue = valueList.stream().map(value -> value.toString()).collect(Collectors.joining(Constant.SEMICOLON)); } sb.append(entry.getKey() + "=" + mapValue); sb.append("&"); } String s = sb.toString(); if (s.endsWith("&")) { s = org.apache.commons.lang.StringUtils.substringBeforeLast(s, "&"); } return s; } }