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

}

發佈了14 篇原創文章 · 獲贊 7 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章