JAVA请求需要Basic身份验证的网页

[来源] 达内    [编辑] 达内   [时间]2013-01-05

户端对用户名和密码进行BASE64编码后传送给服务器。DIGEST的认证方式的细节比较复杂,会经过一系列的加密,所以很难被破译

  通过JAVA抓取页面时,有些页面会返回401(Unauthorized)响应状态码和www-authenticate响应头来要求客户端进行身份认证。这种认证有两种方式:BASIC和DIGEST,BASIC验证要求客户端对用户名和密码进行BASE64编码后传送给服务器。DIGEST的认证方式的细节比较复杂,会经过一系列的加密,所以很难被破译。

  JAVA提供一个用于启用身份认证的类,可以支持HTTP协议中的多个认证方式,.Authenticator,使用方法如下:

  Java 代码

  1.package com.xixuyishi;

  2.

  3.import .BufferedReader;

  4.import .InputStream;

  5.import .InputStreamReader;

  6.import .Authenticator;

  7.import .PasswordAuthentication;

  8.import .URL;

  9.

  10.public class RunHttpSpnego {

  11.

  12. static final String kuser = "username"; // 用户名

  13. static final String kpass = "password"; // 密码

  14. static class MyAuthenticator extends Authenticator {

  15.

  16. @Override

  17. public PasswordAuthentication getPasswordAuthentication() {

  18. return (new PasswordAuthentication(kuser, kpass.toCharArray()));

  19. }

  20. }

  21.

  22. public static void main(String[] args) throws Exception {

  23. Authenticator.setDefault(new MyAuthenticator());

  24. URL url = new URL(args[0]);

  25. InputStream ins = url.openConnection().getInputStream();

  26. BufferedReader reader = new BufferedReader(new InputStreamReader(ins));

  27. String str;

  28. while ((str = reader.readLine()) != null)

  29. System.out.println(str);

  30. }

  31.}

  只需要创建一个继续自Authenticator的类,并且重写其中的getPasswordAuthentication()方法,将用户名和密码放入方法中,这样在需要使用身份认证的地方实现这个类就可以了。

资源下载