public static void main(String[] args) {
//百度的图片url过一段时间,在浏览器里面访问,也会报403,但是现在这个图片是可以打开的。
//如果打不开,麻烦随便换张百度的图片即可。
String url = "http://t12.baidu.com/it/u=2699634842,3384802000&fm=58";
try {
saveTu(url, "D://1.jpg");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void saveTu(final String url, final String filePath) throws Exception {
URL urlR = new URL(url);
HttpURLConnection conn = (HttpURLConnection)urlR.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
//通过输入流获取图片数据
InputStream inStream = conn.getInputStream();
byte[] data = readInputStream(inStream);
File imageFile = new File(filePath);
FileOutputStream outStream = new FileOutputStream(imageFile);
outStream.write(data);
outStream.close();
}
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=inStream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
-------上面是代码,已经加了
conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");可还是不行,谁有办法解决么?
//百度的图片url过一段时间,在浏览器里面访问,也会报403,但是现在这个图片是可以打开的。
//如果打不开,麻烦随便换张百度的图片即可。
String url = "http://t12.baidu.com/it/u=2699634842,3384802000&fm=58";
try {
saveTu(url, "D://1.jpg");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void saveTu(final String url, final String filePath) throws Exception {
URL urlR = new URL(url);
HttpURLConnection conn = (HttpURLConnection)urlR.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
//通过输入流获取图片数据
InputStream inStream = conn.getInputStream();
byte[] data = readInputStream(inStream);
File imageFile = new File(filePath);
FileOutputStream outStream = new FileOutputStream(imageFile);
outStream.write(data);
outStream.close();
}
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=inStream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
-------上面是代码,已经加了
conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");可还是不行,谁有办法解决么?