为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Java

我的开源中国博客地址: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人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消