External Libraries

Jsoup basic authentication example

Jsoup basic authentication example shows how to access website with basic authentication using Jsoup. Example also shows how to send authorization header with Jsoup connection.

How to access website having basic authentication using Jsoup?

HTTP basic authentication uses standard header field to authenticate the client request. Client needs to send “Authorization” header containing user and password to access the resource. Below given is the format of “Authorization” header.

a) User id and password string is created like “username:password” (separated by colon)
b) User id and password string in above format is encoded in base64 encoding.
c) Method of authorization followed by space is put before the encoded user id and password string. So, final “Authorization” header field’s value looks like,

You can use Apache commons codec to encode user id, password string to base64 encoding. You can download the codec from http://commons.apache.org/proper/commons-codec/. Add the library to the classpath so that we can refer to it.

Once you have encoded the user id and password string, you can set “Authorization” header in above given format and connect to the webpage which requires HTTP basic authentication using Jsoup as given below.

Output

Please let us know your views in the comments section below.

 

Tags

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

  • Binit Anil

    I tried the above code to connect to webpage of a router. However it returns the following error “org.jsoup.HttpStatusException: HTTP error fetching URL. Status=401, URL=http://192.168.xx.xx”

    • rahimv

      HTTP 401 is an authentication error. It usually means that the page you are trying to access needs some kind of authentication credentials (login id/password) before you can access it. If you have followed the above steps, the reason could be either
      1) The server is expecting the authentication in method other than BASIC authentication (e.g. DIGEST) or
      2) Credentials you have provided are wrong or not encoded as expected.

      In some cases, server may also send HTTP 401 if it is configured to reject requests from unknown user agents. Try to change the user agent if the above given steps don’t apply.

Join 1000+ fellow learners! Enter your email address below: