How to handle HTTP 403 forbidden error in Java

Sometimes when trying to consume a web service from a java client, you get a 403 forbidden HTTP response code, even though the service is accessible normally from web browsers.

The HTTP 403 forbidden error doesn’t necessarily occur due to missing authentication attributes, some web services would only authorize web browsers or some specific clients to access them, while they deny any requests coming from third-party clients.

# Problem

I am getting HTTP 403 error when retrieving some data from a public web service, while i am able to retrieve them successfully when running the same URL link in web browsers.

This is indeed a very common problem which most developers face when consuming a web service.

# Resolution

This problem is normally resolved by imitating the web browser request so that the web service deals with the java client as if it was a web browser.

The first thing to do is to run the service URL on a web browser and use “live http headers” plugin (or any equivalent) to log the passed header attributes from the browser. Below is a typical request logged from a browser:

As noticed, the “User-Agent” header specifies the name and the type of the client which is trying to access the service, so in order to imitate the web browser we need to add this header to our request. Following is how to add it using HttpUrlConnection:

 

husseinterek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

Be the First to Comment!

avatar