24

Webサービスから大量のPDFリンクを取得しようとしていますが、各リンクのファイルサイズをユーザーに提供したいと思います。

このタスクを実行する方法はありますか?

ありがとう

4

7 に答える 7

44

HEADリクエストを使用すると、次のようなことができます。

private static int getFileSize(URL url) {
    URLConnection conn = null;
    try {
        conn = url.openConnection();
        if(conn instanceof HttpURLConnection) {
            ((HttpURLConnection)conn).setRequestMethod("HEAD");
        }
        conn.getInputStream();
        return conn.getContentLength();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if(conn instanceof HttpURLConnection) {
            ((HttpURLConnection)conn).disconnect();
        }
    }
}
于 2012-10-09T13:09:46.903 に答える
15

受け入れられた回答は、になりがちでNullPointerException、2GiBを超えるファイルでは機能せず、への不要な呼び出しが含まれていますgetInputStream()。修正されたコードは次のとおりです。

public long getFileSize(URL url) {
  HttpURLConnection conn = null;
  try {
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("HEAD");
    return conn.getContentLengthLong();
  } catch (IOException e) {
    throw new RuntimeException(e);
  } finally {
    if (conn != null) {
      conn.disconnect();
    }
  }
}

更新:受け入れられた回答が修正されました。

于 2016-10-31T13:16:31.780 に答える
8

Try to use HTTP HEAD method. It returns the HTTP headers only. The header Content-Length should contain information you need.

于 2012-10-09T13:02:36.310 に答える
4

HTTP応答にはContent-Lengthヘッダーがあるため、URLConnectionオブジェクトにこの値を照会できます。

URL接続が開かれると、次のように試すことができます。

List values = urlConnection.getHeaderFields().get("content-Length")
if (values != null && !values.isEmpty()) {

    // getHeaderFields() returns a Map with key=(String) header 
    // name, value = List of String values for that header field. 
    // just use the first value here.
    String sLength = (String) values.get(0);

    if (sLength != null) {
       //parse the length into an integer...
       ...
    }
}
于 2012-10-09T13:22:37.353 に答える
3

URL接続でgetContentLengthをすでに使用しようとしましたか?サーバーが有効なヘッダーに応答する場合は、ドキュメントのサイズを取得する必要があります。

ただし、Webサーバーがファイルをチャンクで返す場合があることに注意してください。この場合、IIRCのcontent lengthメソッドは、1つのチャンクのサイズ(<= 1.4)または-1(> 1.4)のいずれかを返します。

于 2012-10-09T13:05:04.247 に答える
2

Androidを使用している場合、Javaでの解決策は次のとおりです。

/**@return the file size of the given file url , or -1L if there was any kind of error while doing so*/
@WorkerThread
public static long getUrlFileLength(String url) {
    try {
        final HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("HEAD");
        final String lengthHeaderField = urlConnection.getHeaderField("content-length");
        Long result = lengthHeaderField == null ? null : Long.parseLong(lengthHeaderField);
        return result == null || result < 0L ? -1L : result;
    } catch (Exception ignored) {
    }
    return -1L;
}

そしてKotlinでは:

/**@return the file size of the given file url , or -1L if there was any kind of error while doing so*/
@WorkerThread
fun getUrlFileLength(url: String): Long {
    return try {
        val urlConnection = URL(url).openConnection() as HttpURLConnection
        urlConnection.requestMethod = "HEAD"
        urlConnection.getHeaderField("content-length")?.toLongOrNull()?.coerceAtLeast(-1L)
                ?: -1L
    } catch (ignored: Exception) {
        -1L
    }
}

アプリがAndroidNのものである場合は、代わりにこれを使用できます。

/**@return the file size of the given file url , or -1L if there was any kind of error while doing so*/
@WorkerThread
fun getUrlFileLength(url: String): Long {
    return try {
        val urlConnection = URL(url).openConnection() as HttpURLConnection
        urlConnection.requestMethod = "HEAD"
        urlConnection.contentLengthLong.coerceAtLeast(-1L)
    } catch (ignored: Exception) {
        -1L
    }
}
于 2019-02-28T09:11:17.337 に答える
0

あなたはこれを試すことができます。

private long getContentLength(HttpURLConnection conn) {
    String transferEncoding = conn.getHeaderField("Transfer-Encoding");
    if (transferEncoding == null || transferEncoding.equalsIgnoreCase("chunked")) {
        return conn.getHeaderFieldInt("Content-Length", -1);
    } else {
        return -1;
    }
于 2016-05-03T02:09:17.657 に答える