Jsoup connection with basic access authentication

吃可爱长大的小学妹 提交于 2019-11-26 22:52:23

With HTTP basic access authentication you need to send the Authorization header along with a value of "Basic " + base64encode("username:password").

E.g. (with little help of 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();

// ...

(explicit specification of character encoding in getBytes() is omitted for brevity as login name and pass is often plain US-ASCII anyway; besides, Base64 always generates US-ASCII bytes)

//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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!