Windows 8.1商店应用程序下载文件使用认证和头
本文关键字:文件 认证和 程序下载 应用 Windows | 更新日期: 2023-09-27 18:02:17
我正试图从服务器下载一个文件,并在我的应用程序中添加身份验证和范围标头,所以这个语法正确吗?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
request.Headers["Range"] = "bytes=0-";
request.Credentials = new NetworkCredential("username","password");
当然,代码有读取文件作为一个流和存储它的其他部分,但我关心的范围头和身份验证部分,因为它不工作。
得到一个异常
{"The 'Range' header must be modified using the appropriate property or method.'r'nParameter name: name"}
方法如下:
public async Task<byte[]> DownloadFileAsync(string requestUri)
{
// Service URL
string serviceURL = "http://www.example.com";
// Http Client Handler and Credentials
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new NetworkCredential(username, passwd, domain);
// Initialize Client
HttpClient client = new HttpClient(httpClientHandler)
client.BaseAddress = new Uri(serviceURL);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
// Add Range Header
client.DefaultRequestHeaders.Add("Range", "bytes=0-");
// Deserialize
MemoryStream result = new MemoryStream();
Stream stream = await client.GetStreamAsync(requestUri);
await stream.CopyToAsync(result);
result.Seek(0, SeekOrigin.Begin);
// Bson Reader
byte[] output = null;
using (BsonReader reader = new BsonReader(result))
{
var jsonSerializer = new JsonSerializer();
output = jsonSerializer.Deserialize<byte[]>(reader);
}
return output;
}
我目前使用BSON媒体格式。如果你需要关于后台BSON的额外信息,这里有一篇关于如何实现和使用它的好文章:http://www.strathweb.com/2012/07/bson-binary-json-and-how-your-web-api-can-be-even-faster/
这是另一种方法
var httpClientHandler = new HttpClientHandler();
httpClientHandler.Credentials = new System.Net.NetworkCredential("username", "password");
var client = new HttpClient(httpClientHandler);
System.Net.Http.HttpRequestMessage request = new System.Net.Http.HttpRequestMessage(HttpMethod.Post, new Uri(url));
request.Headers.Range = new RangeHeaderValue(0, null);
HttpResponseMessage response = await client.SendAsync(request);