【发布时间】:2017-06-24 17:24:41
【问题描述】:
以下代码下载具有指定 url 的图像。但我收到一些网址的 403 错误。
根据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);
}
}
}
如果问题重复,请提前道歉。请帮忙。。
【问题讨论】:
标签: java httpurlconnection http-status-code-403