HTTPS請求攜帶證書,雙向認證 - Java

1.首先導入證書到服務器(MAC環境,Linux環境替換對應路徑java home即可)

sudo keytool -import -alias cerName -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home/jre/lib/security/cacerts -file /Downloads/CMCCA_2048.cer

cerName :自定義證書名稱

CMCCA_2048.cer:證書文件

2.Java代碼發送請求

    private final static String PFX_PATH = "/Downloads/xiaochang.cn.p12"; //客戶端證書路徑
	private final static String PFX_PWD = "666666"; //客戶端證書密碼

	public static String sslRequestGet(String url, Map<String, String> heads) throws Exception
	{
		KeyStore keyStore = KeyStore.getInstance("PKCS12");
		InputStream instream = new FileInputStream(new File(PFX_PATH));
		try
		{
			keyStore.load(instream, PFX_PWD.toCharArray());
		}
		finally
		{
			instream.close();
		}
		SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, PFX_PWD.toCharArray()).build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[]
		{ "TLSv1" } // supportedProtocols ,這裏可以按需要設置
				, null // supportedCipherSuites
				, new HostnameVerifier() {

					@Override
					public boolean verify(String hostname, SSLSession session)
					{
                                    //TODO 這裏可以自己做host效驗
						return true;
					}
				});
		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
		try
		{
			HttpGet httpget = new HttpGet(url);
			for (Map.Entry<String, String> entry : heads.entrySet())
			{
				String mapKey = entry.getKey();
				String mapValue = entry.getValue();
				System.out.println(mapKey + ":" + mapValue);
				httpget.addHeader(mapKey, mapValue);
			}
			//            httpost.addHeader("Connection", "keep-alive");// 設置一些heander等
			CloseableHttpResponse response = httpclient.execute(httpget);
			try
			{
				HttpEntity entity = response.getEntity();
				String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");//返回結果
				EntityUtils.consume(entity);
				return jsonStr;
			}
			finally
			{
				response.close();
			}
		}
		finally
		{
			httpclient.close();
		}
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章