仅供参考,转载请注明出处,谢谢
/** * 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)); }