【问题标题】:http request to download a file in java在java中下载文件的http请求
【发布时间】:2015-03-06 12:37:16
【问题描述】:

我对 Java 真的很陌生,所以我希望你能帮助我。 我想编写一个 http 请求以从网站下载文件 (pdf)。 本网站正在使用 cookie。所以我必须发送第一个请求以获取 cookie,然后发送第二个请求以下载文件。

如果可能,我不想使用外部库。

这是我目前为止的:

URLConnection request = null;
    String url = str;
    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    request = new URL(url ).openConnection();

    System.setProperty("http.maxRedirects", "100");

    InputStream in = request.getInputStream();
    File downloadedFile = File.createTempFile("test", ".pdf");
    FileOutputStream out = new FileOutputStream(downloadedFile);        
    byte[] buffer = new byte[1024];
    int len = in.read(buffer);
    while (len != -1) {
        out.write(buffer, 0, len);
        len = in.read(buffer);
        if (Thread.interrupted()) {
            try {
                throw new InterruptedException();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    in.close();
    out.close();
    return downloadedFile.getAbsolutePath();

我的代码似乎什么也没做...

最好的愿望 M1K

【问题讨论】:

  • 在您的问题中,您曾说过您需要有一个 cookie 才能下载文件,但您发布的代码会在连接下载文件之前重置 CookieManager,这意味着之前保存的所有cookies都将被删除。

标签: java http cookies download


【解决方案1】:

如果您在应用程序中使用 spring 框架,请查看是否可以使用 FileCopyUtils 方法的副本并将 fileInputStream 复制到响应输出流,如下所示。

FileCopyUtils.copy(new FileInputStream(file), response.getOutputStream());

【讨论】:

  • 我不认为我在使用 spring 框架......我在 eclipse 中尝试了这个。 !?
  • 文件下载File = File.createTempFile("test", ".pdf"); if (null != deletedFile) { String mimeType = new MimetypesFileTypeMap() .getContentType(downloadedFile); response.setContentType(mimeType); response.setHeader("Content-Disposition", "attachment; filename=" + updatedFile.getName()); FileCopyUtils.copy(new FileInputStream(downloadedFile), response.getOutputStream()); } response 是你的 http 响应对象。
  • 对不起。真的不知道该怎么做... ;) 只是在 eclipse 中尝试这个.... 我只想不使用外部库... ;)
  • public static int copy(InputStream in, OutputStream out) throws IOException { Assert.notNull(in, "No InputStream specified"); Assert.notNull(out, "没有指定输出流");尝试 { int byteCount = 0;字节[] 缓冲区 = 新字节[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead);字节计数 += 字节读取; } out.flush();返回字节数; } 最后 { 尝试 { in.close(); } catch (IOException ex) { } try { out.close(); } 捕捉(IOException ex){ } } }
  • 尝试在你的类中实现和调用该方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-06
  • 2019-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多