僅供參考,轉載請註明出處,謝謝
/** * BASIC認證的https * @param urlStr https請求的地址 * @return */ public static String get(String urlStr) { log.info("url-->" + urlStr); String rs = ""; StringBuffer buffer = new StringBuffer(); DefaultHttpClient client =null; HttpGet get = new HttpGet(urlStr); InputStream instream = null; BufferedReader in = null; HttpResponse response; try { //處理HTTPS請求 client= new SSLClient(); //BASIC認證 client.getCredentialsProvider().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("用戶名","密碼")); //獲取響應 response = client.execute(get); instream = response.getEntity().getContent(); in = new BufferedReader(new InputStreamReader(instream, "utf-8")); String line = ""; while ((line = in.readLine()) != null) { buffer.append(line); } rs = buffer.toString(); System.out.println(rs); } catch (Exception e) { e.printStackTrace(); }finally{ //釋放資源,本身處理一下,不在贅述 } return rs; }
public class SSLClient extends DefaultHttpClient{ //證書處理 private static Logger log = Logger.getLogger(getClass().class); public SSLClient() throws Exception{ super(); SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; log.info("---"); ctx.init(null, new TrustManager[]{tm}, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = this.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); }