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

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 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();
		}
		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;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值