我有以下代码来使用StreamReader读取和处理Http get请求的响应:
try
{
Stream stream = await ExecuteRequestAsync(uriBuilder.Uri, HttpMethod.Get).ConfigureAwait(false);
if (stream != null)
{
using (StreamReader sr = new StreamReader(stream))
{
using (JsonTextReader reader = new JsonTextReader(sr))
{
...
}
}
}
}
catch (Exception ReadingStreamException)
{
}
private async Task<stream> ExecuteRequestAsync(Uri uri, HttpMethod method)
{
Stream stream;
using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, uri))
{
try
{
stopwatch.Start();
using (HttpResponseMessage responseMessage = await this.httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
{
stream = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
}
catch(Exception GettingStreamException)
{
// Error checking code
}
return stream;
}
使用(StreamReader sr = new StreamReader(stream))
的行向ArgumentException类型的ReadingStreamException抛出异常,其详细信息为“Stream is not readable”。上面的代码有问题吗?
答案 0 :(得分:8)
这是因为当您处置HttpResponseMessage
时,它会处置基础流。来自the source:
private HttpContent content;
protected virtual void Dispose(bool disposing)
{
if (disposing && !disposed)
{
disposed = true;
if (content != null)
{
content.Dispose();
}
}
}
您可以复制流,也可以不处理HttpResponseMessage
,因为在将基础流传递给StreamReader
时,无论如何都要处置它。我会选择后者:
private async Task<Stream> ExecuteRequestAsync(Uri uri, HttpMethod method)
{
Stream stream = null;
using (HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, uri))
{
try
{
stopwatch.Start();
HttpResponseMessage responseMessage = await httpClient
.SendAsync(httpRequestMessage)
.ConfigureAwait(false);
stream = await responseMessage.Content.ReadAsStreamAsync()
.ConfigureAwait(false);
}
catch(Exception GettingStreamException)
{
// Error checking code
}
}
return stream;
}