首页 > Web开发 > 详细

getHttpsResponseAsString

时间:2014-11-03 17:53:20      阅读:221      评论:0      收藏:0      [点我收藏+]
public static String getHttpsResponseAsString(String link)
	 {
		 URL url = null;
		 HttpsURLConnection conn = null;
		 StringBuilder result = new StringBuilder("");
		 if(StringUtils.isBlank(link))
		 {
			 logger.error("parameter link should not be empty ");
			 return result.toString();
		 }
		 try
		 {
			 logger.info("opening connection {}",link);
			 url = new URL(link);
			 conn = (HttpsURLConnection) url.openConnection();
		 }
		 catch(Exception e) 
		 {
			 logger.error("Error occur when open url: {}", link, e);
		 }
		 X509TrustManager xtm = new X509TrustManager() {
			@Override
			public void checkClientTrusted(X509Certificate[] arg0, String arg1)
					throws CertificateException {
			}
			@Override
			public void checkServerTrusted(X509Certificate[] arg0, String arg1)
					throws CertificateException {
				
			}
			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		 };
		 
		 try 
		 {
			 TrustManager[] tmArr = {xtm};
			 SSLContext ctx = SSLContext.getInstance("TLS");
			 ctx.init(null, tmArr, null);
			 
			 conn.setSSLSocketFactory(ctx.getSocketFactory());
			 conn.setHostnameVerifier(new HostnameVerifier(){
				@Override
				public boolean verify(String arg0, SSLSession arg1) {
					return true;
				}});
			 
			 logger.info("connecting {} ...",link);
			 conn.connect();
			 logger.info("connection established");
			 
			 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	         String line = "";
	         while ((line = reader.readLine()) != null)
	         {
	        	 result.append(line+"\n");
	         }
		 }
		 catch(Exception ex)
		 {
			 logger.error("Error get response from url: {}", link,  ex);
		 }
		 logger.info("response  from {} is : \n {}",link, result.toString());
         return result.toString();
	 }



getHttpsResponseAsString

原文:http://my.oschina.net/u/1015065/blog/340262

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!