java httpurlconnection 403 but not on web browser

Today i face with a issue when i use java HttpUrlConnection to connect to a site i alway get http code 403. I finally over come that issue after loose a couple of hours. So i write down here  a post and hope can help much people on this prolem. When you search and come to this post i think you can quickly find out solution here.

1-Reason

Some sites will enable to reject when connect to by none browser tool and our connect using HttpUrlConnection violate this rule so the site do not allow to connect.

2-Solution

To solve this issue we can bypass the rule by setting agent header for our connect to those sites

URL url= new URL("site you need connect here");

HttpURLConnection hConnection = (HttpURLConnection) url.openConnection();

hConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");

 

 

Leave a Reply