Java https请求 HttpsURLConnection_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > Java https请求 HttpsURLConnection

Java https请求 HttpsURLConnection

 2016/5/12 5:33:28  dove19900520  程序员俱乐部  我要评论(0)
  • 摘要:publicstaticStringgetHtml(Stringurl)throwsFileNotFoundException,IOException,CertificateException,KeyStoreException,NoSuchAlgorithmException,UnrecoverableKeyException,KeyManagementException{//解决javax.net.ssl.SSLProtocolException:handshakealert
  • 标签:Java URL HTTP
class="java">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;
	}

?

发表评论
用户名: 匿名