6

URLconnectionでファイルのダウンロードの進捗状況を確認したい。それは可能ですか、それとも別のライブラリを使用する必要がありますか?これは私のurlconnection関数です:

public static String sendPostRequest(String httpURL, String data) throws UnsupportedEncodingException, MalformedURLException, IOException {
    URL url = new URL(httpURL);

    URLConnection conn = url.openConnection();
    //conn.addRequestProperty("Content-Type", "text/html; charset=iso-8859-2");
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-2"));
    String line, all = "";
    while ((line = rd.readLine()) != null) {
        all = all + line;
    }
    wr.close();
    rd.close();
    return all;
}

ファイル全体がこの行(またはwearg)でダウンロードされることを理解していますか?:

BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-2"));

それで、このコードでこれを行うことは可能ですか?

4

3 に答える 3

11

HTTPContent-Lengthヘッダーが応答に存在するかどうかを確認するだけです。

int contentLength = connection.getContentLength();

if (contentLength != -1) {
    // Just do (readBytes / contentLength) * 100 to calculate the percentage.
} else {
    // You're lost. Show "Progress: unknown"
}

更新に従って更新します。aの内側をラップし、ループのInputStream内側をBufferedReader読み取ります。while次のようにバイトをカウントできます。

int readBytes = 0;

while ((line = rd.readLine()) != null) {
    readBytes += line.getBytes("ISO-8859-2").length + 2; // CRLF bytes!!
    // Do something with line.
}

+ 2によって食べられるCRLF(キャリッジリターンとラインフィード)バイトをカバーすることですBufferedReader#readLine()。よりクリーンなアプローチはInputStream#read(buffer)、読み取りバイトを計算するために文字から前後にバイトをマッサージする必要がないように、単にそれを読み取ることです。

参照:

于 2011-03-01T23:08:48.937 に答える
0

それをjavax.swing.ProgressMonitorInputStreamでラップします。ただし、Javaは、ストリームへの配信を開始する前に、応答全体をバッファリングする場合があることに注意してください...

于 2011-03-01T23:10:06.833 に答える
0
    BufferedReader rd = new BufferedReader(new InputStreamReader(new FilterInputStream(conn.getInputStream())
    {
        public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException
        {
            int count = super.read(buffer, byteOffset, byteCount);
            // do whatever with count, i.e. mDownloaded += count;
            return count;
        }
    }, "ISO-8859-2"));
于 2014-05-21T22:10:55.730 に答える