apache httpclient使用证书进行https请求

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.net.ssl.SSLContext;

import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.junit.Test;

public class AppTest {
	@Test
	public void test() throws Exception {
		String url = "https://127.0.0.1:8888/cmcc";
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpClient httpClient = null;
		if (url.startsWith("https")) {
			File cert = new File("D:\\test\\logs\\cert.jks");
			String keystore = "mocohttps";
			// Trust own CA and all self-signed certs
			SSLContext sslcontext = SSLContexts.custom()
					.loadTrustMaterial(cert, keystore.toCharArray(), new TrustSelfSignedStrategy()).build();
			// Allow TLSv1 protocol only
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
					null, NoopHostnameVerifier.INSTANCE);
			httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
		} else {
			httpClient = HttpClients.createDefault();
		}

		try (CloseableHttpClient _httpClient = httpClient;
				CloseableHttpResponse res = _httpClient.execute(httpGet);) {
			if (res != null) {
				StatusLine sl = res.getStatusLine();
				if (sl != null) {
					System.out.println(sl.getStatusCode());
					StringBuilder builder = new StringBuilder();
					try (InputStream is = res.getEntity().getContent();
							InputStreamReader isr = new InputStreamReader(is);
							BufferedReader br = new BufferedReader(isr);) {
						String line = br.readLine();
						while(line != null) {
							builder.append(line);
							line = br.readLine();
						}
						System.out.println("响应结果:" + builder.toString());
					}
				}
			}
		}
	}

}

 

转载于:https://my.oschina.net/lhplj/blog/1603999

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值