论坛首页 入门技术论坛

解决 用URL访问远程文件报403错误

浏览 2612 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-11-18   最后修改:2009-06-07
URL url = new URL("http://jzhua.iteye.com/rss");

URLConnection conn = url.openConnection();

// 只要将该语句加上既可以实现
conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");

InputStream is = conn.getInputStream();
byte[] bts = new byte[2048];
ByteArrayOutputStream bout = new ByteArrayOutputStream();
FileOutputStream fout = new FileOutputStream("c:\\test.xml");
int n;
while ((n = is.read(bts)) != -1) {
fout.write(bts, 0, n);
fout.flush();
bts = new byte[2048];
}

URL url = new URL(rss); 
URLConnection uc = (HttpURLConnection) url.openConnection(); 
uc.setRequestProperty("User-agent", "IE/6.0"); 
//设置超时 
uc.setConnectTimeout(3000); 
InputStream in = uc.getInputStream(); 

使用上面这段代码就可以解决那个会等待的问题啦,只要设置一个连接超时时间就可以啦。

出现Server returned HTTP response code: 403的主要问题是:
通常是因为服务器的安全设置不接受Java程序作为客户端访问,解决方案是设置客户端的User Agent
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics