码迷,mamicode.com
首页 > 其他好文 > 详细

HTTPClient 发送HTTPS请求

时间:2014-09-03 16:54:27      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:httpclient

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>



HTTPClient 发送HTTPS请求

标签:httpclient

原文地址:http://blog.csdn.net/killeraction/article/details/39028519

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!