码迷,mamicode.com
首页 > Web开发 > 详细

getHttpsResponseAsString

时间:2014-11-03 17:54:45      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:http   io   ar   os   java   sp   on   log   cti   

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   io   ar   os   java   sp   on   log   cti   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!