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; } }
相关文章推荐
- Apache 大三方法HTTP请求链接响应之HttpClient的GET和POST工具类封装
- HttpClient封装,get请求和post请求,文件下载和上传
- Java学习笔记———《http的get请求和post请求及封装的工具类》
- android HttpClient get请求与post请求工具类
- HttpClient 的GET(带参数)、POST请求方式,工具类方法
- android HttpClient get请求与post请求工具类
- HttpClient get和HttpClient Post请求的方式获取服务器的返回数据
- swift3.0 URLSession网络请求工具类封装(get请求,post请求)
- Qt--Http请求封装(Get Post)
- 轻松把玩HttpClient之封装HttpClient工具类(五),携带Cookie的请求
- 轻松把玩HttpClient之封装HttpClient工具类(五),携带Cookie的请求
- java apache commons HttpClient发送get和post请求的学习整理
- 【Angular】angular-HttpClient 与服务器通讯 Get Post Put Delete Http 拦截器 请求讲解
- 【Angular】angular-HttpClient 与服务器通讯 Get Post Put Delete Http 拦截器 请求讲解
- Android 网络请求方式之HttpClient,GET,POST,PUT请求使用方法
- 轻松把玩HttpClient之封装HttpClient工具类(五),携带Cookie的请求
- httpClient Post例子,Http 四种请求访问代码 HttpGet HttpPost HttpPut HttpDelete
- 简单封装Http的Get和Post请求
- HttpClient Post、get 请求方式
- ASIHTTPRequest 对GET POST 请求简单封装