使用URL连接下载文件

时间:2015-04-01 10:35:20

标签: java

我有以下代码,它下载文件,但Adobe说该文件是损坏的。文件大74KB,但我只能下载大约27KB。你能告诉我什么是错的吗?感谢

@WebServlet("/GetData")
public class GetData extends HttpServlet {
private static final long serialVersionUID = 1L;

private static final int BUFFER_SIZE = 4096;

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    String typ = ".pdf";
    int totalBytesRead = 0;


    String sep = File.separator;
    String saveDir = "C:" + sep + "downloads";
    String link ="/g02pepe/portal?token=9059829732446568452&action_16502593.mainContent_root_cntXYZ_cntShow_actShowFirstRow::km_XXXXXXX-XXXX::=&frontletId=XXXXX";

    String adress = "https://XXXXXXX.XXXX.de/g02pepe/entry?rzid=XC&rzbk=0032&trackid=piwikad277d23c35b4990";
    String together = adress + link;
    String username = "XXXXXXXXX";
    String password = "XXXXXXXXX";
    String authString = username + ":" + password;
    System.out.println("Auth string: " + authString);
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);

    try {
        URL url = new URL(adress);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0");
        connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        connection.addRequestProperty("Referer", together);
        System.out.println("Connected to " + together);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.connect();

        int responseCode = connection.getResponseCode();
        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = connection.getHeaderField("Content-Disposition");
            String contentType = connection.getContentType();
            int contentLength = connection.getContentLength();

            if (disposition != null) {
                // extracts file name from header field
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10,
                            disposition.length() - 1);
                }
            } else {
                // extracts file name from URL
                fileName = adress.substring(adress.lastIndexOf("/") + 1,
                        adress.length());
            }
            System.out.println("Content-Type = " + contentType);
            System.out.println("Content-Disposition = " + disposition);
            System.out.println("Content-Length = " + contentLength);
            System.out.println("fileName = " + fileName);


            InputStream in = connection.getInputStream();

            String saveFilePath = saveDir + File.separator + "Entgeltinformationen"  + typ;             

            // opens an output stream to save into file
            FileOutputStream outputStream = new FileOutputStream(saveFilePath);

            int bytesRead = -1;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((bytesRead = in.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                 totalBytesRead += bytesRead;
            }
            System.out.println("Total Bytes read "  + totalBytesRead);

            outputStream.close();
            in.close();

            System.out.println("File downloaded");
        } else {
            System.out
                    .println("No file to download. Server replied HTTP code: "
                            + responseCode);
        }

        connection.disconnect();

        out.println("Download done!");

    } catch (Exception e) {
        e.printStackTrace();
    }
   }
}

我要下载的文件是PDF。

0 个答案:

没有答案