我需要在从服务器下载文件时显示进度条,但我不知道如何获取文件大小。我使用像这样的POST方法
HttpPost httppost = new HttpPost(url);
Inputstream toDown = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("p1", p1));
nameValuePairs.add(new BasicNameValuePair("p2", p2));
nameValuePairs.add(new BasicNameValuePair("p3", p3));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode()!=200){
toDown = null;
}
else{
toDown = response.getEntity().getContent();
}
但我不知道如何处理这些信息以获取文件大小
答案 0 :(得分:0)
并非所有服务器都支持HEAD标头。以下powershell代码无需下载文件本身即可获取文件大小:
$param1 = 0
$param2 = 0
$param3 = "https://URI"
# Add the necessary .NET assembly
Add-Type -AssemblyName System.Net.Http
# Create the HttpClient object
$client = New-Object -TypeName System.Net.Http.Httpclient
$client.DefaultRequestHeaders.Range = New-Object -TypeName System.Net.Http.Headers.RangeHeaderValue($param1, $param2)
$HttpMethod = New-Object -TypeName System.Net.Http.HttpMethod("get")
$HttpRequestMessage = New-Object -TypeName System.Net.Http.HttpRequestMessage($HttpMethod, $param3)
$HttpResponseMessage = $client.SendAsync($HttpRequestMessage)
$HttpResponseMessage.wait();
$size = $HttpResponseMessage.result.content.headers.contentrange.length
echo $size
在Powershell 5.1.17134.1,Win 10上进行了测试