2

http://aula.au.dk/main/document/document.php?action=download&id=%2F%D8velsesvejledning+2012.pdfからファイルをダウンロードしようとしています が、pdf ではないようです。このコードでダウンロードしようとすると

import java.io.*;
import java.net.*;

public class DownloadFile {

public static void download(String address, String localFileName) throws IOException {
    URL url1 = new URL(address);

    byte[] ba1 = new byte[1024];
    int baLength;
    FileOutputStream fos1 = new FileOutputStream(localFileName);

    try {
        // Contacting the URL
        System.out.print("Connecting to " + url1.toString() + " ... ");
        URLConnection urlConn = url1.openConnection();

        // Checking whether the URL contains a PDF
        if (!urlConn.getContentType().equalsIgnoreCase("application/pdf")) {
            System.out.println("FAILED.\n[Sorry. This is not a PDF.]");
        } else {
            try {

                // Read the PDF from the URL and save to a local file
                InputStream is1 = url1.openStream();
                while ((baLength = is1.read(ba1)) != -1) {
                    fos1.write(ba1, 0, baLength);
                }
                fos1.flush();
                fos1.close();
                is1.close();


            } catch (ConnectException ce) {
                System.out.println("FAILED.\n[" + ce.getMessage() + "]\n");
            }
        }

    } catch (NullPointerException npe) {
        System.out.println("FAILED.\n[" + npe.getMessage() + "]\n");
    }
}
}

ここで私を助けてもらえますか?

4

3 に答える 3

1

http://aula.au.dk/main/document/document.php?action=download&id=%2F%D8velsesvejledning+2012.pdfは pdf ではありません。Web サイトでエラーが発生するため、スクリプトが機能しません。

ファイル /data/htdocs/dokeos184/www/main/inc/tool_navigation_menu.inc.php の 70 行目の SQL エラー

于 2012-10-18T23:15:12.823 に答える
0

マルティが言ったように、問題の根本的な原因はスクリプトが失敗するという事実です。動作中の pdf リンクでプログラムをテストしましたが、問題なく動作します。

この場合、これは役に立ちませんでしたが、HttpURLConnectionは URLConnection の特殊なサブクラスであり、http サーバーとの通信をはるかに簡単にします。たとえば、エラー コードへの直接アクセスなどです。

HttpURLConnection urlConn = (HttpURLConnection) url1.openConnection();
// check the responsecode for e.g. errors (4xx or 5xx) 
int responseCode = urlConn.getResponseCode();
于 2012-10-18T23:08:20.483 に答える
0

2 つのライブラリを使用した 2 ステップのプロセス。

// 1. Use Jsoup to get the response.
Response response= Jsoup.connect(location)
                   .ignoreContentType(true)
                   // more method calls like user agent, referer, timeout 
                   .execute();

// 2. Use Apache Commons to write the file 
FileUtils.writeByteArrayToFile(new File(path), response.bodyAsBytes());
于 2013-11-29T11:19:16.333 に答える