1

从服务器下载文件时我需要显示进度条,但我不知道如何获取文件大小。我使用这样的 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();
        }

但我不知道如何处理这些信息来获取文件大小

4

1 回答 1

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 上测试

于 2019-08-26T14:03:30.307 回答