下面的代碼會下載具有指定URL的圖像。但是,我得到了一些URL的403錯誤。的Java禁錯誤的代碼,但不能與瀏覽器(2)
根據這一link,我嘗試使用調用setRequestProperty(),但仍然是我的問題並沒有解決。我想不出我犯或有什麼更多的,我應該添加到我的代碼錯誤了嗎?
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);
}
}
}
對不起,如果問題是重複的。請幫助..
對不起,沒有奏效。 –