Search code examples
javajsoupbasic-authentication

Jsoup connection with basic access authentication


Is there a way in Jsoup to load a document from a website with basic access authentication?


Solution

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

    E.g.

    String username = "foo";
    String password = "bar";
    String login = username + ":" + password;
    String base64login = Base64.getEncoder().encodeToString(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)