getHttpsResponseAsString

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)