`
welcome66
  • 浏览: 397625 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

HttpURLConnection安全认证式访问方法

阅读更多

 在使用http访问网站时,有时候网站需要提供用户名和密码,才能访问到具体内容。我们用代码怎么来填入这些认证信息呢?

    下面是一些具体的代码:

    URL realUrl = new URL(url);

 

    HttpURLConnection httpUrlConnection = (HttpURLConnection) realUrl.openConnection();        

    httpUrlConnection.setRequestProperty("accept", "*/*");

    httpUrlConnection.setRequestProperty("connection", "Keep-Alive");

    httpUrlConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0;               Windows NT 5.1;SV1)");

    httpUrlConnection.setRequestProperty("content-Type", "text/xml");

    httpUrlConnection.setConnectTimeout(60000);

    //设置用户名和密码

    String user = "www.test.com";

    String pwd = "mysys";

    String auth = user+":"+pwd;

    //对其进行加密

     byte[] rel = Base64.encodeBase64(auth.getBytes());

    String res = new String(rel);

    //设置认证属性

    httpUrlConnection.setRequestProperty("Authorization","Basic " + res);

    httpUrlConnection.setReadTimeout(readTimeout);

    httpUrlConnection.connect();

    Map<String, List<String>> map = httpUrlConnection.getHeaderFields();

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics