Java https请求 HttpsURLConnection

public static String getHtml(String url) throws FileNotFoundException,
			IOException, CertificateException, KeyStoreException,
			NoSuchAlgorithmException, UnrecoverableKeyException,
			KeyManagementException {
		//解决javax.net.ssl.SSLProtocolException: handshake alert:  unrecognized_name的异常
		System.setProperty("jsse.enableSNIExtension", "false");
		String msg = null;

		// KeyStore trust = KeyStore.getInstance("PKCS12");
		// trust.load(new FileInputStream("c:/https_key/src/server.p12"), kp);

		SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null,
				new TrustStrategy() {
					// 信任所有
					public boolean isTrusted(X509Certificate[] chain,
							String authType) throws CertificateException {
						return true;
					}
				}).build();
		// SSLContext sslContext = SSLContexts.custom()
		// .loadKeyMaterial(ks, kp)//.loadTrustMaterial(trust)
		// .build();
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				sslContext, new String[] { "TLSv1" }, null,
				SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
		CloseableHttpClient httpclient = HttpClients.custom()
				.setSSLSocketFactory(sslsf).build();
		try {

			HttpGet httpget = new HttpGet(url);

			CloseableHttpResponse response = httpclient.execute(httpget);
			try {
				HttpEntity entity = response.getEntity();

				// System.out.println("----------------------------------------");
				// System.out.println(response.getStatusLine());
				// 获取响应返回状态码

				// 获取应答输入流
				// System.out.println("Response content length: " +
				// entity.getContentLength());
				BufferedReader bufferedReader = new BufferedReader(
						new InputStreamReader(entity.getContent(), "utf-8"));
				String tmp;
				StringBuffer text = new StringBuffer();
				while ((tmp = bufferedReader.readLine()) != null) {
					// System.out.println(tmp);
					text.append(tmp);
				}
				msg = text.toString();
				EntityUtils.consume(entity);
			} finally {
				response.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpclient.close();
		}

		return msg;
	}

猜你喜欢

转载自dove19900520.iteye.com/blog/2297434