This question already has an answer here:
I want to open a link from url : "http://www.kohls.com/search.jsp?search=jacket&submit-search=web-regular", sometimes i get:
java.io.IOException: Server returned HTTP response code: 403 for URL. But it's ok when open the url using browser. Below is part of my code:
URL url = new URL("http://www.kohls.com/search.jsp?search=jacket&submit-search=web-regular");
InputStream is = url.openConnection().getInputStream();
error detail
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://www.kohls.com/search.jsp?N=0&search=jacket&WS=96 at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627) at Links.main(Links.java:41)
The particular webserver you are trying to access is checking the
User-Agent
HTTP header and denying access to anything that doesn't look like a normal browser, to prevent bots (which is probably what you are writing).You just need to set the header as part of your request in Java and it will work.
How you set the header will depend on how you are making the connection, but if you are using a simple URLConnection then this will work:
Normally a "real"
User-Agent
contains lots of extra info, but that webserver seems to look only for the basic browser type.You can prove this using
wget
with and without the-U
User-Agent option: