手记

java如何请求BASIC认证的https协议

我的开源中国博客地址:https://my.oschina.net/u/2486137/blog/1523329\

/**
     * 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)); 

        }  
1人推荐
随时随地看视频
慕课网APP

热门评论

原创咋不给分啊,``````````````


查看全部评论