Jsoup与基本访问身份验证的连接

时间:2011-10-06 20:12:25

标签: java jsoup http-basic-authentication

Jsoup中是否有办法从具有基本访问身份验证的网站加载文档?

2 个答案:

答案 0 :(得分:32)

使用HTTP basic access authentication,您需要发送Authorization标头以及值"Basic " + base64encode("username:password")

E.g。 (Apache Commons Codec Base64)的帮助很少:

String username = "foo";
String password = "bar";
String login = username + ":" + password;
String base64login = new String(Base64.encodeBase64(login.getBytes()));

Document document = Jsoup
    .connect("http://example.com")
    .header("Authorization", "Basic " + base64login)
    .get();

// ...

(为了简洁起见,省略了getBytes()中字符编码的明确规范,因为登录名和传递通常是普通的US-ASCII;此外,Base64总是生成US-ASCII字节)< / em>的

答案 1 :(得分:5)

//Log in
Response res = Jsoup
    .connect("url")
    .data("loginField", "login")
    .data("passwordField", "password")
    .method(Method.POST)
    .execute();

Document doc = res.parse();


//Keep logged in
Map<String, String> cookies = res.cookies();

Document doc2 = Jsoup
    .connect("url")
    .cookies(cookies)
    .get();