1. 程式人生 > >HTTPClient 傳送HTTPS請求

HTTPClient 傳送HTTPS請求

HTTPClient 傳送HTTP請求就不多說了, 現在給出傳送HTTPS請求, 主要思路是忽略證書驗證.

/**
	 * 
	 * @param url
	 * @param contextType  "image/jpeg","application/Json"
	 * @return
	 */
	public static byte[] sendHttpsGetUrl(HttpClient httpClient1 ,String url,String contextType) {
		
		// 響應內容
		byte[] bs = null;
		
		// 建立預設的httpClient例項
//		HttpClient httpClient = new DefaultHttpClient();
		HttpClient httpClient =		httpClient1;
		
		// 建立TrustManager
		X509TrustManager xtm = new X509TrustManager() {
			public void checkClientTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}
			
			public void checkServerTrusted(X509Certificate[] chain,
					String authType) throws CertificateException {
			}
			
			public X509Certificate[] getAcceptedIssuers() {
				return new X509Certificate[] {};
			}
		};
		try {
			SSLContext ctx = SSLContext.getInstance("SSL");
			
			// 使用TrustManager來初始化該上下文,TrustManager只是被SSL的Socket所使用
			ctx.init(null, new TrustManager[] { xtm }, null);
			
			SSLSocketFactory sf = new SSLSocketFactory(
					ctx,
					SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			Scheme sch = new Scheme("https", 443, sf);
			httpClient.getConnectionManager().getSchemeRegistry().register(sch);
			// 建立HttpPost
			HttpGet httpPost = new HttpGet(url); 
			httpPost.setHeader("content-type", contextType);
			// 執行POST請求
			HttpResponse response = httpClient.execute(httpPost); 
			// 獲取響應實體
			HttpEntity entity = response.getEntity();
			 bs = IOUtils.toByteArray(entity.getContent());
			 if (null != entity) {
					EntityUtils.consume(entity); // Consume response content
				}
			return bs;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 關閉連線,釋放資源
//			httpClient.getConnectionManager().shutdown(); 
		}
		return bs;
	}
  如果連續的請求不需要帶cookie,可以改造下此方法, 方法引數中不帶HttpClient即可,此情況下記得在愛Finally塊中關閉連線。

  下面給出Maven required:

<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.2.3</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>