配置類
package com.gzkj.admin.config;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter4;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* <Description>
*
* @author CJJ
* @version 1.0
* @createDate 2019/09/05 16:13
*/
@Configuration
@ConditionalOnClass(value = {RestTemplate.class, HttpClient.class})
public class RestfulConfig {
/* 連接池的最大連接數默認爲0 */
@Value("${remote.maxTotalConnect:1}")
private int maxTotalConnect;
/* 單個主機的最大連接數 */
@Value("${remote.maxConnectPerRoute:200}")
private int maxConnectPerRoute;
/* 連接超時默認2s */
@Value("${remote.connectTimeout:120000}")
private int connectTimeout;
/* 讀取超時默認30s */
@Value("${remote.readTimeout:180000}")
private int readTimeout;
//創建HTTP客戶端工廠
private ClientHttpRequestFactory createFactory() {
if (this.maxTotalConnect <= 0) {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(this.connectTimeout);
factory.setReadTimeout(this.readTimeout);
return factory;
}
HttpClient httpClient = HttpClientBuilder.create().setMaxConnTotal(this.maxTotalConnect)
.setMaxConnPerRoute(this.maxConnectPerRoute).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(
httpClient);
factory.setConnectTimeout(this.connectTimeout);
factory.setReadTimeout(this.readTimeout);
return factory;
}
//初始化RestTemplate,並加入spring的Bean工廠,由spring統一管理
@Bean
@ConditionalOnMissingBean(RestTemplate.class)
public RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate(this.createFactory());
List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
//重新設置StringHttpMessageConverter字符集爲UTF-8,解決中文亂碼問題
HttpMessageConverter<?> converterTarget = null;
for (HttpMessageConverter<?> item : converterList) {
if (StringHttpMessageConverter.class == item.getClass()) {
converterTarget = item;
}
break;
}
if (null != converterTarget) {
converterList.remove(converterTarget);
}
converterList.add(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
//加入FastJson轉換器
converterList.add(new FastJsonHttpMessageConverter4());
return restTemplate;
}
}
簡單工具類
package com.gzkj.admin.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* HTTP 請求工具類
*
* @author cjj
* @date 2019年7月23日
*/
@Slf4j
@Component
public class RestfulUtils<T> {
@Autowired
RestTemplate restTemplate;
public RestfulUtils() {
}
public Object getWithHeaders(String url) {
return requestFor(url, HttpMethod.GET, null, null);
}
public Object postWithHeaders(String url, JSONObject body) {
return requestFor(url, HttpMethod.POST, body, null);
}
public Object requestFor(String url, HttpMethod method, JSONObject requestBody) {
return requestFor(url, method, requestBody, null);
}
public Object requestFor(String url, HttpMethod method, JSONObject requestBody, Class<Object> tClass) {
HttpEntity httpEntity = init(method, requestBody);
System.out.println("url:" + url);
System.out.println("method:" + method);
System.out.println("body:" + Optional.ofNullable(requestBody).map(v -> v.toJSONString()).orElse(""));
ResponseEntity<Object> o = restTemplate.exchange(url, method, httpEntity, Object.class);
HttpHeaders headers = o.getHeaders();
Object body = o.getBody();
if (tClass == null) {
return body;
}
if (body instanceof List) {
List<Map<String, Object>> o1 = (List<Map<String, Object>>) body;
String s = JSON.toJSONString(o1);
return JSONArray.parseArray(s, tClass);
} else if (body instanceof Map) {
Map<String, Object> o1 = (Map<String, Object>) body;
String s = JSON.toJSONString(o1);
return JSON.parseObject(s, tClass);
}
return JSON.toJSONString(body);
}
private HttpEntity init(HttpMethod method, JSONObject body) {
HttpHeaders headers = new HttpHeaders();
// headers.set(HttpHeaders.AUTHORIZATION, restDto.getBasic());
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<MultiValueMap<String, String>> httpEntity = null;
if (method == HttpMethod.GET) {
httpEntity = new HttpEntity<>(headers);
} else if (method == HttpMethod.POST) {
httpEntity = new HttpEntity(body.toJSONString(), headers);
}
return httpEntity;
}
}