public class HttpClientUtil {
private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private static PoolingHttpClientConnectionManager connManager = null;
private static CloseableHttpClient httpclient = null;
static {
try {
SSLContext sslContext = SSLContexts.custom().useTLS().build();
sslContext.init(null,
new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
X509Certificate[] certs, String authType) {
}
}}, null);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext))
.build();
connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
httpclient = HttpClients.custom().setConnectionManager(connManager).build();
// Create socket configuration
SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
connManager.setDefaultSocketConfig(socketConfig);
// Create message constraints
MessageConstraints messageConstraints = MessageConstraints.custom()
.setMaxHeaderCount(200)
.setMaxLineLength(2000)
.build();
// Create connection configuration
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE)
.setCharset(Consts.UTF_8)
.setMessageConstraints(messageConstraints)
.build();
connManager.setDefaultConnectionConfig(connectionConfig);
connManager.setMaxTotal(200);
connManager.setDefaultMaxPerRoute(20);
} catch (KeyManagementException e) {
logger.error("KeyManagementException", e);
} catch (NoSuchAlgorithmException e) {
logger.error("NoSuchAlgorithmException", e);
}
}
public static String postJsonBody(String url, int timeout, Map<String, Object> map, String encoding){
HttpPost post = new HttpPost(url);
try {
post.setHeader("Content-type", "application/json");
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(timeout)
.setConnectTimeout(timeout)
.setConnectionRequestTimeout(timeout)
.setExpectContinueEnabled(false).build();
post.setConfig(requestConfig);
String str1 = JsonUtil.objectToJson(map).replace("\\", "");
post.setEntity(new StringEntity(str1, encoding));
logger.info("[HttpUtils Post] begin invoke url:" + url + " , params:"+str1);
CloseableHttpResponse response = httpclient.execute(post);
try {
HttpEntity entity = response.getEntity();
try {
if(entity != null){
String str = EntityUtils.toString(entity, encoding);
logger.info("[HttpUtils Post]Debug response, url :" + url + " , response string :"+str);
return str;
}
} finally {
if(entity != null){
entity.getContent().close();
}
}
} finally {
if(response != null){
response.close();
}
}
} catch (UnsupportedEncodingException e) {
logger.error("UnsupportedEncodingException", e);
} catch (Exception e) {
logger.error("Exception", e);
} finally {
post.releaseConnection();
}
return "";
}
@SuppressWarnings("deprecation")
public static String invokeGet(String url, Map<String, String> params, String encode, int connectTimeout,
int soTimeout) {
String responseString = null;
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(connectTimeout)
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectTimeout).build();
StringBuilder sb = new StringBuilder();
sb.append(url);
int i = 0;
for (Entry<String, String> entry : params.entrySet()) {
if (i == 0 && !url.contains("?")) {
sb.append("?");
} else {
sb.append("&");
}
sb.append(entry.getKey());
sb.append("=");
String value = entry.getValue();
try {
sb.append(URLEncoder.encode(value, "UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.warn("encode http get params error, value is "+value, e);
sb.append(URLEncoder.encode(value));
}
i++;
}
logger.info("[HttpUtils Get] begin invoke:" + sb.toString());
HttpGet get = new HttpGet(sb.toString());
get.setConfig(requestConfig);
try {
CloseableHttpResponse response = httpclient.execute(get);
try {
HttpEntity entity = response.getEntity();
try {
if(entity != null){
responseString = EntityUtils.toString(entity, encode);
}
} finally {
if(entity != null){
entity.getContent().close();
}
}
} catch (Exception e) {
logger.error(String.format("[HttpUtils Get]get response error, url:%s", sb.toString()), e);
return responseString;
} finally {
if(response != null){
response.close();
}
}
logger.info(String.format("[HttpUtils Get]Debug url:%s , response string %s:", sb.toString(), responseString));
} catch (SocketTimeoutException e) {
logger.error(String.format("[HttpUtils Get]invoke get timout error, url:%s", sb.toString()), e);
return responseString;
} catch (Exception e) {
logger.error(String.format("[HttpUtils Get]invoke get error, url:%s", sb.toString()), e);
} finally {
get.releaseConnection();
}
return responseString;
}
public final static int connectTimeout = 5000;
/**
* HTTPS请求,默认超时为5S
* @param reqURL
* @param params
* @return
*/
public static String connectPostHttps(String reqURL, Map<String, String> params) {
String responseContent = null;
HttpPost httpPost = new HttpPost(reqURL);
try {
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(connectTimeout)
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectTimeout).build();
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
httpPost.setEntity(new UrlEncodedFormEntity(formParams, Consts.UTF_8));
httpPost.setConfig(requestConfig);
// 绑定到请求 Entry
for (Map.Entry<String, String> entry : params.entrySet()) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
// 执行POST请求
HttpEntity entity = response.getEntity(); // 获取响应实体
try {
if (null != entity) {
responseContent = EntityUtils.toString(entity, Consts.UTF_8);
}
} finally {
if(entity != null){
entity.getContent().close();
}
}
} finally {
if(response != null){
response.close();
}
}
logger.info("requestURI : "+httpPost.getURI()+", responseContent: " + responseContent);
} catch (ClientProtocolException e) {
logger.error("ClientProtocolException", e);
} catch (IOException e) {
logger.error("IOException", e);
} finally {
httpPost.releaseConnection();
}
return responseContent;
}
}
使用CXF暴露您的REST服务:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 引入CXF下面的配置文件 -->
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<!-- 将Bean托管给Spring -->
<bean id="roomService" class="com.platform.restful.demo.RoomService">
</bean>
<bean id="userService" class="com.platform.restful.demo.UserService">
</bean>
<!-- 配置需要暴露的BeanService -->
<jaxrs:server id="restContainer" address="/">
<jaxrs:serviceBeans>
<ref bean="roomService" />
<ref bean="userService" />
</jaxrs:serviceBeans>
</jaxrs:server>
</beans>