专业的JAVA编程教程与资源

网站首页 > java教程 正文

使用java做爬虫获取网络资源下载403错误解决办法

temp10 2024-09-10 20:55:33 java教程 23 ℃ 0 评论

前言:

在做爬虫的时候,有时候需要下载爬到连接的URL。

使用java做爬虫获取网络资源下载403错误解决办法

比如:String url = “http://www.kaigejava.com/uplode/pdf/xxxxx.pdf";

如果使用File file = new File(url );

发现file处理后成了:http:\www.kaigejava.com\uplode\pdf\xxxxx.pdf

然后使用file的判断方法。提示获取不到。

那么使用java的file对象怎么获取网络资源?

code:

代码如下:

publicclass FileTests {

publicstaticvoid main(String[] args) throws Exception {

String fileName = "d96c6dcfda2559c5865db89388d28cbf.pdf";

String fileUrl = "http://10.10.10.242:82/xxx/files/d96c6dcfda2559c5865db89388d28cbf.pdf";

String downPath = "C:\\Users\\kaigejava\\Desktop\\xss";

downUrlTxt(fileName,fileUrl,downPath);

}

publicstaticvoid downUrlTxt(String fileName,String fileUrl,String downPath){

File savePath = new File(downPath);

if (!savePath.exists()) {

savePath.mkdir();

}

String[] urlname = fileUrl.split("/");

intlen = urlname.length-1;

String uname = urlname[len];//获取文件名

try {

File file = new File(savePath+"/"+uname);//创建新文件

if(file!=null && !file.exists()){

file.createNewFile();

}

OutputStream oputstream = new FileOutputStream(file);

URL url = new URL(fileUrl);

URLConnection uc ;

uc = url.openConnection();

uc.addRequestProperty("User-Agent",

"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");

uc.setDoInput(true);//设置是否要从 URL 连接读取数据,默认为true

uc.connect();

InputStream iputstream = uc.getInputStream();

System.out.println("file size is:"+uc.getContentLength());//打印文件长度

byte[] buffer = newbyte[4*1024];

intbyteRead = -1;

while((byteRead=(iputstream.read(buffer)))!= -1){

oputstream.write(buffer, 0, byteRead);

}

oputstream.flush();

iputstream.close();

oputstream.close();

} catch (Exception e) {

System.out.println("读取失败!");

e.printStackTrace();

}

System.out.println("生成文件路径:"+downPath+fileName);

}

}

下载提示:

需要注意的:

如果提示:Server returned HTTP response code: 403 for URL

这个错误。

有可能是服务器拒绝了java直接访问。

所以需要使用下面选中的部分。伪装成浏览器请求。

如下:



百科:

User-Agent:

如果您觉得有用请分享给您的朋友。

【欢迎关注微信公众号:凯哥java】

开心一刻:

1、老师:“生铁是铁,熟铁是铁,铁锤一敲铁打铁。谁能对下联?”

小明:“男人是人,女人是人,床板一响人造人。”

老师:“滚出去!”

2、老师:“都是一个老师教的,为什么人家就学得好呢?”

小明:“因为不是一个父母生的。”

老师:“滚出去!”

3、初中开学典礼校长谈早恋。

校长:早恋犹如青色的苹果,过早的品尝只会让你感到苦涩。

小明:苹果熟透了还能轮到我么。

校园:快滚,不然我开除你!

4、老师:为什么鸡蛋是圆形的,不是方形的呢?

小明:老师,你有考虑过母鸡的感受吗?

老师!@#!@#





Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表