您的位置:首页 > 理论基础 > 计算机网络

HttpClient(get/post)请求封装成工具类

2018-01-17 17:15 561 查看
package app.utils;

import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.net.ssl.SSLContext;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

/**
* @author Rock
*
*/
public final class SpiderUtil {

public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
CertificateException, IOException {
System.out.println(testPostJsonEntity());
System.out.println(testPostFormEntity());
}

/**
* Post json数据样例
*
* @return
* @throws KeyManagementException
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws CertificateException
* @throws IOException
*/
public static String testPostJsonEntity() throws KeyManagementException, NoSuchAlgorithmException,
KeyStoreException, CertificateException, IOException {
String url = "https://www.isrcb.com/portal/WebEXyfChildProductQuery.do";
JSONObject requestJSON = new JSONObject();
requestJSON.put("PrdId", "0001");
requestJSON.put("PrdType", "");
requestJSON.put("ChildPrdId", "0000000001");
requestJSON.put("_locale", "zh_CN");
requestJSON.put("BankId", "9998");
requestJSON.put("ModuleBank", "DBP");
requestJSON.put("LoginType", "P");
StringEntity stringEntity = new StringEntity(requestJSON.toJSONString(), ContentType.APPLICATION_JSON);
String response = post(url, stringEntity, "json", null, null, true, false);
return Optional.ofNullable(response).orElse(null);
}

/**
* Post Form表单数据样例
*
* @return
* @throws KeyManagementException
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws CertificateException
* @throws IOException
*/
public static String testPostFormEntity() throws KeyManagementException, NoSuchAlgorithmException,
KeyStoreException, CertificateException, IOException {
String url = "https://zxyh.nbcb.com.cn/desktop/InvestListQry.do";
List<NameValuePair> formData = new ArrayList<NameValuePair>();
formData.add(new BasicNameValuePair("BankId", "9999"));
formData.add(new BasicNameValuePair("NewProduct", "Y"));
formData.add(new BasicNameValuePair("OS", "PC"));
formData.add(new BasicNameValuePair("PageCount", "5"));
formData.add(new BasicNameValuePair("PageNum", "1"));
formData.add(new BasicNameValuePair("SortRule", "0"));
formData.add(new BasicNameValuePair("_ChannelId", "pc"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formData, Consts.UTF_8);
String response = post(url, formEntity, "form", null, null, true, false);
return Optional.ofNullable(response).orElse(null);
}

/**
*
* @param url
*            请求URL
* @param entity
*            发送实体
* @param contentType
*            发送类型[xml|json|text]
* @param jksFilePath
*            秘钥库文件绝对路径
* @param jksPwd
*            秘钥库文件密码
* @param httpsFlag
*            是否https请求
* @param jksFlag
*            是否需要证书,CA认证过的不需要jks秘钥库
* @return
* @throws KeyManagementException
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws CertificateException
* @throws IOException
*/
public static String post(String url, HttpEntity entity, String contentType, String jksFilePath, String jksPwd,
boolean httpsFlag, boolean jksFlag) throws KeyManagementException, NoSuchAlgorithmException,
KeyStoreException, CertificateException, IOException {
RequestConfig globalConfig = null;
RequestConfig localConfig = null;
CloseableHttpClient httpClient = null;
HttpPost httpPost = new HttpPost(url);
if (httpsFlag && jksFlag) {
if (MethodUtil.isNull(jksFilePath)) {
return "jksFilePath cannot be null";
}
if (MethodUtil.isNull(jksPwd)) {
return "jksPwd cannot be null";
}
globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(new File(jksFilePath), jksPwd.toCharArray(), new TrustSelfSignedStrategy())
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(globalConfig).build();
localConfig = RequestConfig.copy(globalConfig).setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
} else {
globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
localConfig = RequestConfig.copy(globalConfig).setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
}
httpPost.setConfig(localConfig);
httpPost.setEntity(entity);
if (entity instanceof StringEntity) {
if (MethodUtil.isNull(contentType)) {
return "contentType cannot be null:[json|xml|text|form]";
}
if ("json".equals(contentType)) {
((StringEntity) entity).setContentType(ContentType.APPLICATION_JSON.toString());
} else if ("xml".equals(contentType)) {
((StringEntity) entity).setContentType(ContentType.APPLICATION_XML.toString());
} else if ("text".equals(contentType)) {
((StringEntity) entity).setContentType(ContentType.TEXT_PLAIN.toString());
} else if ("form".equals(contentType)) {
((StringEntity) entity).setContentType(ContentType.APPLICATION_FORM_URLENCODED.toString());
}
}
ResponseHandler<String> handler = handler();
String response = httpClient.execute(httpPost, handler);
httpClient.close();
return Optional.ofNullable(response).orElse(null);
}

/**
*
* @param url
*            请求URL
* @param jksFilePath
*            秘钥库文件绝对路径
* @param jksPwd
*            秘钥库文件密码
* @param httpsFlag
*            是否https请求
* @param jksFlag
*            是否需要证书,CA认证过的不需要jks秘钥库
* @return
* @throws KeyManagementException
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws CertificateException
* @throws IOException
*/
public static String get(String url, String jksFilePath, String jksPwd, boolean httpsFlag, boolean jksFlag)
throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException,
IOException {
RequestConfig globalConfig = null;
RequestConfig localConfig = null;
CloseableHttpClient httpClient = null;
HttpGet httpGet = new HttpGet(url);
if (httpsFlag && jksFlag) {
if (MethodUtil.isNull(jksFilePath)) {
return "jksFilePath cannot be null";
}
if (MethodUtil.isNull(jksPwd)) {
return "jksPwd cannot be null";
}
globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(new File(jksFilePath), jksPwd.toCharArray(), new TrustSelfSignedStrategy())
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFac
4000
tory(sslcontext, new String[] { "TLSv1" },
null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(globalConfig).build();
localConfig = RequestConfig.copy(globalConfig).setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
} else {
globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
localConfig = RequestConfig.copy(globalConfig).setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
}
httpGet.setConfig(localConfig);
ResponseHandler<String> handler = handler();
String response = httpClient.execute(httpGet, handler);
httpClient.close();
return Optional.ofNullable(response).orElse(null);
}

/**
* @return
*/
private static <T> ResponseHandler<T> handler() {
ResponseHandler<T> loginHandler = new ResponseHandler<T>() {
@SuppressWarnings("unchecked")
@Override
public T handleResponse(final HttpResponse response) throws IOException {
StatusLine statusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
if (entity == null) {
throw new ClientProtocolException("Response contains no content");
}
entity = new BufferedHttpEntity(entity);
String responseAsString = EntityUtils.toString(entity, "UTF-8");
return (T) responseAsString;
}
};
return loginHandler;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HttpClint