在C#中将`system.net.http.httpresponemessage`转换为`system.io.stream`

时间:2017-05-28 10:04:04

标签: c#

我的CurrentCode:

using (var client = new HttpClient
{
    Timeout = TimeSpan.FromMilliseconds(2000)
})
{
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var response = await client.GetAsync(new Uri(Constants.mUrl));

    // convert stream to string
    StreamReader reader = new StreamReader(respons);

    var myItems = Newtonsoft.Json.JsonConvert.DeserializeObject<ModelClassObject>(response);

    return myItems;
}

1 个答案:

答案 0 :(得分:2)

对回复的内容使用ReadAsStreamAsync

using(var response = await client.GetAsync(new Uri(Constants.mUrl))) {
    var stream = await response.Content.ReadAsStreamAsync();
    //...
}

如果要直接从响应中解析JOSN,那么

using(var response = await client.GetAsync(new Uri(Constants.mUrl))) {
    var myItems = await response.Content.ReadAsAsync<ModelClassObject>();
    return myItems;
}