1. 程式人生 > >使用HttpClient4.3.1模擬Http請求與無信任證書訪問Https

使用HttpClient4.3.1模擬Http請求與無信任證書訪問Https

package com.paic.pmit.core.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.paic.pafa.app.biz.service.BusinessServiceException;
import com.paic.pmit.core.biz.service.impl.AbstractInvokeGroovy;


/**
 * 模擬Http請求
 * @author:EX-WANGYIDE001
 * @date:2016-10-1上午10:29:18
 *--------------------
 *修改記錄,含日期,作者,修改內容
 */
public class public_equipment_HttpClientUtils extends AbstractInvokeGroovy  {

	Logger logger = Logger.getLogger(this.getClass());
	
	/**
	 * 傳送http請求
	 * @author:EX-WANGYIDE001
	 * @date:2016-10-1上午10:29:14
	 * @param url 請求URL
	 * @param parameter	請求引數
	 * @param requestCharset 編碼格式
	 * @return
	 * @throws BusinessServiceException
	 */
	public String sendHttpRequest(String url, Map<String, String> parameter, String requestCharset) throws BusinessServiceException {
		logger.info("處理Http請求:"+url);
		long start = System.currentTimeMillis(); 
		String result = null;
		CloseableHttpClient http = null;
		try {
			//建立HttpClient
			//HttpHost proxy = new HttpHost("10.36.232.126",8080);代理
			RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(60000).build();
			HttpClientBuilder builder = HttpClientBuilder.create();
			http = builder.build();
			//http = createSSLClientDefault();
			//post請求
			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(config);
			//引數佇列
			httpPost.setEntity(new UrlEncodedFormEntity(parameterConvert(parameter),requestCharset));
			//執行請求
			HttpResponse response = http.execute(httpPost);
			//響應處理
			int httpStatus = response.getStatusLine().getStatusCode();
			if (httpStatus == HttpStatus.SC_OK){
				HttpEntity entity = response.getEntity();
				if(entity != null){
					result = EntityUtils.toString(entity, requestCharset);
					logger.info("返回引數:"+result);
				}
			}else{
				throw new BusinessServiceException("服務方介面響應異常, httpStatus: " + httpStatus);
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("http請求引數處理異常",e);
			throw new BusinessServiceException("http請求引數處理異常");
		} catch (ClientProtocolException e) {
			logger.error("http請求發生HTTP異常",e);
			throw new RuntimeException("http請求發生HTTP異常");
		} catch (IOException e) {
			logger.error("http請求發生IO異常",e);
			throw new RuntimeException("http請求發生IO異常");
		} finally{
			logger.info("耗時: " + (System.currentTimeMillis() - start) + " 毫秒");
			if(http!=null){
				try {
					http.close();
				} catch (IOException e) {
					logger.error("釋放資源  close error:"+e);
				}
			}
		}
		return result;
	}
	
	/**
	 * 轉換引數
	 * @author:EX-WANGYIDE001
	 * @date:2016-10-1下午2:59:37
	 * @param parameter
	 * @return
	 */
	private List<NameValuePair> parameterConvert(Map<String,String> parameter){
		List<NameValuePair> results = new ArrayList<NameValuePair>(parameter.size());
		Set<Entry<String, String>> entrySet = parameter.entrySet();
		for (Iterator<Entry<String, String>> iter = entrySet.iterator(); iter.hasNext();) {
			Entry<String, String> entry = iter.next();
			results.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
		}
		return results;
	}
	
	/**
	 * 處理Https請求證書
	 * @author:EX-WANGYIDE001
	 * @date:2016-10-1下午3:50:34
	 * @return
	 *//*
	private CloseableHttpClient createSSLClientDefault(){
		try {
             SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                 //信任所有證書
                 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                     return true;
                 }
             }).build();
             SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(sslContext);
             return HttpClients.custom().setSSLSocketFactory(sslFactory).build();
         } catch (Exception e) {
        	 logger.error("處理Https證書異常",e);
         }
         return  HttpClients.createDefault();
	}*/
	
	/**
	 * 測試方法
	 * @author:EX-WANGYIDE001
	 * @date:2016-10-2上午9:58:51
	 * @param args
	 * @throws Exception
	 *//*
	public static void main(String args[]) throws Exception {
		
		public_equipment_HttpClientUtils http = new public_equipment_HttpClientUtils();
		Map<String,String> parameter = new HashMap<String,String>();
		parameter.put("credentials", "123456123");
		http.sendHttpRequest("測試地址", parameter, "UTF-8");
		
		
	}*/
	
	
	
}


相關推薦

使用HttpClient4.3.1模擬Http請求信任證書訪問Https

package com.paic.pmit.core.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; im

使用httpclient4.3.X模擬post請求登陸網站獲取cookie資訊的操作

             眾所周知,httpclient可以模擬登陸操作,下面我就來個例項測試一下,順便也回憶下這個開源工具的使用,直接上例子吧! package com.pyc.search.crawler.node.login; import java.io.IO

使用HttpClient4.4 模擬http請求

3、使用HttpClient進行網路處理的基本步驟 (1)通過get的方式獲取到Response物件。 CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet =

http協議(模擬http請求httphttps的區別)

模擬http請求 這裡我用的win03 首先開啟cmd,然後輸入Telnet www.baidu.com 80 後按回車(此時是黑屏狀態) 然後利用快捷鍵 “ctrl+]”來開啟telnet

淺談HTTP請求響應

tcp 方法 刪除 請求 連接 客戶機 cin tex 文件 HTTP協議用於客戶端和服務器之間的通信,請求訪問的一段是客戶端,提供資源響應的一段是服務器端。 HTTP通信是采用請求應答的方式來進行的,客戶端發出請求,服務器響應。如果沒有客戶端的請求,服務器端是不進行任

HTTP請求響應協議

使用 6.0 agent 顯示 禁用 說明 含義 需要 保持 HTTP(hypertext transport protocol),即超文本傳輸協議。這個協議詳細規定了瀏覽器和萬維網服務器之間互相通信的規則 HTTP就是一個通信規則,通信規則規定了客戶端發送給服務器的內容

http請求傳參

nbsp content lin user apple data dss man url 這並不算是文章,暫時只做粗略地記錄,以免忘記,因此會顯得雜亂無章,隨便抓了幾個包和對postman截圖,日後有空再完善 1、get方式 只有一種方式,那就是在url後面跟參

ruby on rails模擬HTTP請求錯誤發生:end of file reached

ats ace post result tcs 後來 nec scu microsoft 在文章 Ruby On Rails中REST API使用演示樣例——基於雲平臺+雲服務打造自己的在線翻譯工具 中,利用ruby的Net::HTTP發起http請求訪問IBM Blu

python利用requests模擬http請求請求

requests python 請求頭 header post 一、通過requests發送請求之前一直使用urllib以及urllib2模擬http請求發送,在實際場景中,我們需要造自己定義好的header、body等等,使用urllib很麻煩,很偶然的機會,接觸到了requests,可

postman模擬http請求

返回結果 man 分享 名稱 當我 http響應 cati json數據 nbsp 一、http請求(僅描述get和post請求) 1、get請求:在URL中直接展示參數名稱和數值,請求長度有限制 例如,請求userid=1的用戶信息,url:http://hostname

C#模擬HTTP請求並發送二進制

keep lose type response ica con new urn for public static String Submit(String methodName) { string postData = "this is post data";/

php模擬http請求的兩種姿勢

php http curl CURL$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$connectTimeout); curl_setop

Http協議以及模擬http請求發送數據

我們 public w3c 註意 -s accep 情況 hat 資源定位 1 為什麽要使用http協議   假設我現在有兩個客戶端瀏覽器,一個是google,一個是IE瀏覽器;我現在有兩個服務器,一個是tomcat,一個是JBoss;在最初的情況下是:如果google要往

封裝HttpClient進行http請求https請求

src empty one key-value fin finally 發送post請求 工具類 catch 一.https忽略證書 /** * 用於進行Https請求的HttpClient * * @author joey * */ public class

Java 模擬 HTTP 請求

exe execute source -h org gethost apach enc target 使用方法 HttpClient http://hc.apache.org/httpcomponents-client-ga/httpclient/dependency-in

教你如何用Python模擬http請求(GET,POST)

客戶 python TE all pos get 傳輸協議 AD 服務 模擬http請求有什麽用呢? 我們現在使用的所有需要使用網絡的:軟件 應用 app 網站裏面的絕大部分功能都是通過http協議來工作的 什麽是http協議? http協議,超文本傳輸協議(HTTP,Hy

curl java 模擬http請求

col ont font nbsp pri tin throw url while curl java 模擬http請求 直接上代碼: 1 public static void main(String args[]) throws Exception { 2 3

爬蟲-2.HTTP請求響應

英文 應該 gecko 進一步 cfm n-1 獲取數據 字符集 max HTTP和HTTPS HTTP協議(HyperText Transfer Protocol,超文本傳輸協議):是一種發布和接收 HTML頁面的方法。 HTTPS(Hypertext Transfer

文加圖, 理解Http請求響應

工作 clas 我不 響應頭 oid 情況下 share 高清 設置代理 1. http請求和響應步驟 在講解OkHttp之前, 我們首先來個高清大圖, 看下http請求的整個步驟, 有個整體概念. 2. http每一步詳細內容 在一次完整的HTTP通信過程中, Web瀏

用Java發起HTTP請求獲取狀態碼(含狀態碼列表)

滿足 null timeout etc default 語法 訪問 網頁 trace 轉自:https://blog.csdn.net/xyw591238/article/details/51072697 在使用Java請求Web程序比如訪問WebService接口時,通