Skip to content
Advertisement

Downloading image from Url in java.Server returned HTTP response code: 403 error. How can I get the connection to work?

I am trying to downloada picture from a certain url, but cant do so because I somehow have to give the right userclient to the website.I am sure the problem is that I cant give the user client while using the Url class, because the page can be accesed via browser. I tried using proxy and Urlconnection but couldnt get it to work. Please share your toughts on the matter!

My code is the following:

JavaScript

Advertisement

Answer

Instead of using ImageIO.read(URL), which limits you to the default behavior of the URL’s underlying URLConnection, use ImageIO.read(InputStream).

This allows you to use any HTTP client library – including the basic HttpURLConnection, which you can get from (HttpURLConnection)url_kep.openConnection(). Using that, you can set headers such as User-Agent, if that’s the header required by the site, or other headers such as Referer which are sometimes used to prevent deep-linking.

Once you set up all the headers and any other request options, you can get an InputStream from the client object, and pass that to ImageIO.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement