Ikuta Erika

导航

HttpURLConnection 添加代理

        //创建代理服务器
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("www.proxyaddress.com", 8080));
        //设置代理的用户名密码
        Authenticator.setDefault(new MyAuth("用户名", "密码"));
        // 设定连接的相关参数
        URL url = new URL(locationUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);

    static class MyAuth extends Authenticator
    {
        private String user;
        private String pass;
        
        public MyAuth(String user, String pass)
        {
            this.user  = user;
            this.pass = pass;
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return  new PasswordAuthentication(user, pass.toCharArray());
        }
    }

 

posted on 2016-09-05 17:04  风灯  阅读(3418)  评论(0编辑  收藏  举报