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:
import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.Proxy; import java.net.SocketAddress; import java.net.URL; import java.net.URLConnection; import javax.imageio.ImageIO; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.highgui.Highgui; public class KepLetolto { public static void main(String[] args) throws IOException { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); File file = new File("tempjpeg"); SocketAddress address = new java.net.InetSocketAddress("xyz.com", 8080); // Create an HTTP Proxy using the above SocketAddress. Proxy proxy = new Proxy(Proxy.Type.HTTP, address); URL url_kep =new URL("http://www.theouthousers.com/images/templates/thumbnails/128058/bayfinger_size3.png"); ImageIO.write(ImageIO.read(url_kep), "jpeg", file); Mat uj = Highgui.imread("temp.jpeg" ,Highgui.CV_LOAD_IMAGE_COLOR); } }
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
.