java添加HTTP基本认证(Basic Authentication)

来源:互联网 发布:剑三正太捏脸数据附图 编辑:程序博客网 时间:2024/04/20 12:21

关于HTTP基本认证(Basic Authentication)的原理请参考:http://blog.csdn.net/kkdelta/article/details/28419625

如果某接口采用Http Basic Authentication基本认证,一般由服务方提供用户名密码,当需要访问这个接口时,我们需要在代码中加入认证。

//访问前添加认证(MyAuthenticator是自定义内部类)Authenticator.setDefault(new MyAuthenticator());URL getUrl =new URL(newUrl);// 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,// 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection        HttpURLConnection connection =(HttpURLConnection) getUrl.openConnection();        connection.connect();        ……        ……        ……

MyAuthenticator内部类:

static class MyAuthenticator extends Authenticator{        public PasswordAuthentication getPasswordAuthentication(){            return (new PasswordAuthentication(username,password.toCharArray()));        }    }
原创粉丝点击