我想使用 HttpClient 从服务器获取文件。为此,我使用 GetStreamAsAsync() 方法。我想检查是否正确获取流,或者如果出现问题则获取异常。
我已经读过这个问题,问了同样的问题,但答案是抛出了 HttpRequestException,但在我的情况下,代码继续执行而没有问题。
据说如果我使用 SendAsAsync() 方法,它会返回 HttpResponseMessage,但在我的情况下不需要使用此方法,并且 GetStreamAsAsync() 没有 HttpResponseMessage 属性。
我使用的代码是这样的:
公共异步任务
try
{
using Stream fichero = await _clienteHttp.GetStreamAsync(paramRutaFichero).ConfigureAwait(false);
using MemoryStream ms = new();
await fichero.CopyToAsync(ms);
return ms.ToArray();
}
catch (UriFormatException ex)
{
throw new Exception(ex.Message);
}
catch (InvalidOperationException ex)
{
throw new Exception(ex.Message);
}
catch (HttpRequestException ex)
{
throw new Exception(ex.Message);
}
catch (TaskCanceledException ex)
{
throw new Exception(ex.Message);
}
}
那么我能否知道我是否正确获取了流?
谢谢。
您可以将代码修改为以下内容:
public async Task<byte[]> SolicitarFicherosAsync(Uri paramRutaFichero)
{
try
{
using HttpResponseMessage response = await _clienteHttp.GetAsync(paramRutaFichero, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
using Stream fichero = await
response.Content.ReadAsStreamAsync().ConfigureAwait(false);
using MemoryStream ms = new();
await fichero.CopyToAsync(ms);
return ms.ToArray();
}
catch (HttpRequestException ex)
{
if (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
throw new Exception("File not found.");
}
else if (ex.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
throw new Exception("Unauthorized access.");
}
else
{
throw new Exception($"HTTP error occurred: {ex.Message}");
}
}
catch (Exception ex)
{
// Handle any other exceptions
throw new Exception($"An error occurred: {ex.Message}");
}
}
要检查是否使用
GetStreamAsync()
正确检索流并处理任何异常,您可以更改代码以使用 GetAsync()
和 HttpCompletionOption.ResponseHeadersRead
代替。
这允许您检索
HttpResponseMessage
,而无需下载整个响应正文。然后您可以在 EnsureSuccessStatusCode()
上调用 HttpResponseMessage
以确保 HTTP 响应状态代码指示成功。
然后,如果状态代码成功,它将使用
ReadAsStreamAsync()
的 Content 属性上的 HttpResponseMessage
将响应正文作为流读取。