Webサービスから大量のPDFリンクを取得しようとしていますが、各リンクのファイルサイズをユーザーに提供したいと思います。
このタスクを実行する方法はありますか?
ありがとう
Webサービスから大量のPDFリンクを取得しようとしていますが、各リンクのファイルサイズをユーザーに提供したいと思います。
このタスクを実行する方法はありますか?
ありがとう
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();
}
}
}
受け入れられた回答は、になりがちで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();
}
}
}
更新:受け入れられた回答が修正されました。
Try to use HTTP HEAD method. It returns the HTTP headers only. The header Content-Length
should contain information you need.
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...
...
}
}
URL接続でgetContentLengthをすでに使用しようとしましたか?サーバーが有効なヘッダーに応答する場合は、ドキュメントのサイズを取得する必要があります。
ただし、Webサーバーがファイルをチャンクで返す場合があることに注意してください。この場合、IIRCのcontent lengthメソッドは、1つのチャンクのサイズ(<= 1.4)または-1(> 1.4)のいずれかを返します。
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
}
}
あなたはこれを試すことができます。
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;
}