Below code downloads an image with specified url. But I am getting 403 error for some urls.
According to this link, I tried using setRequestProperty() but still my problem isn't solved. I couldn't figure out the mistake that I made or is there anything more that I should add to my code?
import java.io.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLConnection;
import java.net.HttpURLConnection;
class Crawler{
public static void main(String args[]){
String address = "http://szcdn1.raagalahari.com/dec2016/hd/anupama-parameswaran-premam-hd-photos/anupama-parameswaran-premam-hd-photos294.jpg";
Connection connection1 = new Connection();
connection1.connector(address);
}
}
class Connection{
void connector(String s){
try{
URL url = new URL(s);
URLConnection uc = url.openConnection();
HttpURLConnection http_connection = (HttpURLConnection) uc;
http_connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.63 Safari/537.36");
http_connection.connect();
ImageDownload downloader = new ImageDownload();
downloader.download(url);
}catch(Exception e) {
System.out.println(e);
}
}
}
class ImageDownload{
void download(URL u){
try
{
InputStream in = new BufferedInputStream(u.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf))){
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("C://3.jpg");
fos.write(response);
fos.close();
} catch(IOException e){
System.out.println(e);
}
}
}
Sorry in advance if the question is duplicate. Please help..