使用apache http客户端下载时,Pdf文件已损坏

时间:2017-09-01 04:08:14

标签: java apache pdf download apache-httpclient-4.x

我正在尝试通过网络自动下载pdf文件。在浏览器中手动打开时,它采用PDF Acrobat格式。我可以通过单击页面中的打印或保存选项来下载。 我写了Downloader.java附件。它与sample PDF available in the network一起工作正常。 但是当我尝试从以下URL下载文件时

URL("https://myapplication.com//mod.dll?tenant=tnt_name&b_action=cognosViewer&ui.action=run&ui.object=%2Fcontent%2Ffolder%5B%40name%3D%27basic+reports_101%27%5D+%2Freport%5B%40name%3D%27KJL99.xml%27%5D&ui.name=KJL99.xml&**run.outputFormat**=PDF&run.prompt=false&SESSkIONID=6121&p_R5_FRONTPG=-&JOB=1122&run.print=falseSaved");

已成功下载,但无法打开:

  

Acrobat无法打开'[文件名],因为它不是a   支持的文件类型或因为文件已损坏

尝试了几个论坛的一些解决方案,但他们没有修复它。我能得到一些帮助吗? 以下是Downloader.java的代码段:

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;enter code here
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;


public class Downloader {

    public File download(URL url, File dstFile) {

        CloseableHttpClient httpclient = HttpClients.custom()
                    .setRedirectStrategy(new LaxRedirectStrategy()) // adds HTTP REDIRECT support to GET and POST methods 
                    .build();
        try {
            HttpPost get = new HttpPost(url.toURI()); // we're using GET but it could be via POST as well
            File downloaded = httpclient.execute(get, new FileDownloadResponseHandler(dstFile));
            return downloaded;
        } catch (Exception e) {
            throw new IllegalStateException(e);
        } finally {
            IOUtils.closeQuietly(httpclient);
        }
    }

    static class FileDownloadResponseHandler implements ResponseHandler<File> {

        private final File target;

        public FileDownloadResponseHandler(File target) {
            this.target = target;
        }

        @Override
        public File handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            InputStream source = response.getEntity().getContent();
            FileUtils.copyInputStreamToFile(source, this.target);
            return this.target;
        }

    }

}

0 个答案:

没有答案