无法通过java下载文件 - 在浏览器中工作

时间:2013-04-16 07:52:09

标签: java http url

我现在做的事情是这样的:

class FileDownloader{
    public static void downloadFile(URL myUrl, File myOutputFile) throws IOException{
    HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("UserAgent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11");
    InputStream is = conn.getInputStream();
    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(myOutputFile));

    byte buf[] = new byte[1024];
    int k = 0;
    while ((k = is.read(buf)) != -1) {
        stream.write(buf, 0, k);
    }
    is.close();
    stream.close();
     }
 }

下载文件。但在某些网站上下载不起作用,我转发到错误页面。当我在Chrome或Firefox甚至Internet Explorer中打开完全相同的URL时,它可以正常工作。

是否有一些RequestProperty我可以设置让这个东西工作?或者我应该使用另一个lib,比如Apache HTTP吗?

附加信息:我无法查看Web服务器日志,也无法调整网络服务器设置。

0 个答案:

没有答案
相关问题