1.写一个SSLClient类,继承至HttpClient
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
//用于进行Https请求的HttpClient
public class SSLClient extends DefaultHttpClient{
public SSLClient() throws Exception{
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override zz
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
2.写一个HttpClientTemplate类
/**
*
*/
package com.sf.ibs.ams.ups.constants;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
public class HttpClientTemplate {
private static final Log logger = LogFactory.getLog(HttpClientTemplate.class);
private final static String DEFAULT_CONTENT_TYPE = "application/xml;charset=utf-8";
private final static String DEFAULT_KEEP_ALIVE = "false";
private String contentType;
private String keepAlive;
private HttpClient httpClient;
private HttpResponseContext httpResponseContext;
public HttpClientTemplate(int sslPort, int connectionTimeout, int soTimeout){
this.httpClient = new SSLDefaultHttpsClient(sslPort);
this.httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
this.httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
this.httpClient.getParams().setParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 1024);
this.httpClient.getParams().setParameter(CoreConnectionPNames.SO_KEEPALIVE, false);
}
public <T> T doPost(String uri, Map<String, String> params, Class<T> clazz) throws URISyntaxException{
URI url = new URI(uri);
try {
return this.doPost(url, params, clazz);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public <T> T doPost(URI uri, Map<String, String> params, Class<T> clazz) throws Exception {
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader(HTTP.CONTENT_TYPE, null == contentType ? DEFAULT_CONTENT_TYPE : contentType);
httpPost.setHeader(HTTP.CONN_KEEP_ALIVE, null == keepAlive ? DEFAULT_KEEP_ALIVE : keepAlive);
httpPost.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
List<NameValuePair> paramList = null;
if(null != params && !params.isEmpty()){
paramList = new ArrayList<NameValuePair>();
for(Map.Entry<String, String> param : params.entrySet()){
paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
}
if(null != paramList && !paramList.isEmpty()){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
try {
httpClient.execute(httpPost, (HttpContext) httpResponseContext);
} catch (IOException e) {
e.printStackTrace();
}
return httpResponseContext.getResponseMessage(clazz);
}
@Deprecated
public <T> T doGet(String uri, Map<String, String> params, Class<T> clazz) throws Exception{
URI url = new URI(uri);
return this.doGet(url, params, clazz);
}
@Deprecated
public <T> T doGet(URI uri, Map<String, String> params, Class<T> clazz) throws Exception{
HttpGet httpGet = new HttpGet(uri);
httpGet.setHeader(HTTP.CONTENT_TYPE, null == contentType ? DEFAULT_CONTENT_TYPE : contentType);
httpGet.setHeader(HTTP.CONN_KEEP_ALIVE, null == keepAlive ? DEFAULT_KEEP_ALIVE : keepAlive);
httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
if(null != params && !params.isEmpty()){
HttpParams param = new BasicHttpParams();
for(Map.Entry<String, String> map : params.entrySet()){
param.setParameter(map.getKey(), map.getValue());
}
httpGet.setParams(param);
}
try {
httpClient.execute(httpGet, (HttpContext) httpResponseContext);
} catch (IOException e) {
e.printStackTrace();
}
return httpResponseContext.getResponseMessage(clazz);
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public HttpClient getHttpClient() {
return httpClient;
}
public void setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
}
public String getKeepAlive() {
return keepAlive;
}
public void setKeepAlive(String keepAlive) {
this.keepAlive = keepAlive;
}
public HttpResponseContext getHttpResponseContext() {
return httpResponseContext;
}
public void setHttpResponseContext(HttpResponseContext httpResponseContext) {
this.httpResponseContext = httpResponseContext;
}
}
3.自定义
package com.sf.ibs.ams.ups.constants;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
/**
* @author 01367620
*
*/
public class UPSHttpClientTemplate extends HttpClientTemplate {
private final static String DEFAULT_CONTENT_TYPE = "application/xml;charset=utf-8";
private final static String DEFAULT_KEEP_ALIVE = "false";
public UPSHttpClientTemplate(int sslPort, int connectionTimeout, int soTimeout){
super(sslPort, connectionTimeout, soTimeout);
}
public <T> T doPost(URI uri, Map<String, String> params, Class<T> clazz) throws Exception {
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader(HTTP.CONTENT_TYPE, null == this.getContentType() ? DEFAULT_CONTENT_TYPE : this.getContentType());
httpPost.setHeader(HTTP.CONN_KEEP_ALIVE, null == this.getKeepAlive() ? DEFAULT_KEEP_ALIVE : this.getKeepAlive());
httpPost.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
try {
httpPost.setEntity(new StringEntity(
params.get(UPSConstants.REQUEST_XML)));
} catch (Exception e1) {
e1.printStackTrace();
}
try {
this.getHttpClient().execute(httpPost, (HttpContext) this.getHttpResponseContext());
} catch (IOException e) {
e.printStackTrace();
}
return this.getHttpResponseContext().getResponseMessage(clazz);
}
}
4.自定义返回类型
package com.sf.ibs.ams.ups.constants;
import com.sf.ibs.ams.ups.order.exception.ResponseErrorException;
/**
* @author 01367620
*
*/
public interface HttpResponseContext{
public <T> T getResponseMessage(Class<T> clazz) throws ResponseErrorException;
}
5.
package com.sf.ibs.ams.ups.constants;
import java.io.IOException;
import javax.xml.bind.JAXBException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.util.EntityUtils;
import com.sf.ibs.ams.ups.order.exception.ResponseErrorException;
import com.sf.ibs.ams.util.XMLUtils;
/**
* @author 01367620
*
*/
public class UPSHttpResponseContext extends BasicHttpContext implements HttpResponseContext {
private static final Log logger = LogFactory.getLog(UPSHttpResponseContext.class);
public UPSHttpResponseContext(){
super();
}
public <T> T getResponseMessage(Class<T> clazz) throws ResponseErrorException{
HttpResponse response = (HttpResponse) this.getAttribute(ExecutionContext.HTTP_RESPONSE);
if(null == response || null == response.getStatusLine()){
logger.error("HTTP_RESPONSE Attribute or Status is empty or null.");
throw new ResponseErrorException("HTTP_RESPONSE Attribute is empty or null.");
}
int statusCode = response.getStatusLine().getStatusCode();
if(HttpStatus.SC_OK != statusCode){
logger.error("HTTP_RESPONSE Status is not OK, status code is:"+statusCode);
throw new ResponseErrorException("Response status error, Status Code is: "+statusCode+",\nreason phrase is:"+response.getStatusLine().getReasonPhrase());
}
HttpEntity responseEntity = response.getEntity();
if(null == responseEntity){
logger.error("Response Entity is empty or null.");
throw new ResponseErrorException("There is not response from remote or response is null, please double check the remote server.");
}
return this.handlerMessage(responseEntity, clazz);
}
private <T> T handlerMessage(HttpEntity responseEntity, Class<T> clazz){
String responseXml;
try {
responseXml = EntityUtils.toString(responseEntity);
return XMLUtils.unmarshaller(responseXml, clazz);
} catch (ParseException | IOException | JAXBException e) {
e.printStackTrace();
}
return null;
}
}