最简单的方法来读取WebResponse的响应

时间:2010-12-26 11:39:22

标签: c#

    private void RespCallback(IAsyncResult asynchronousResult)
    {
        try
        {
            WebRequest myWebRequest1 = (WebRequest)asynchronousResult.AsyncState;
            // End the Asynchronous response.
           WebResponse webResponse = myWebRequest1.EndGetResponse(asynchronousResult);

        }
        catch (Exception)
        {

            //TODO:Log the error
        }

    }

现在拥有webResponse对象,阅读其内容的最简单方法是什么?

3 个答案:

答案 0 :(得分:48)

我只想在WebClient上使用异步方法 - 更容易使用:

        WebClient client = new WebClient();
        client.DownloadStringCompleted += (sender,args) => {
            if(!args.Cancelled && args.Error == null) {
                string result = args.Result; // do something fun...
            }
        };
        client.DownloadStringAsync(new Uri("http://foo.com/bar"));

但要回答这个问题;假设它是 text ,就像(注意你可能需要指定编码):

        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            string result = reader.ReadToEnd(); // do something fun...
        }

答案 1 :(得分:12)

如果响应来自XML,这是一种方法。

        HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://www.yoururl.com");

        WebResponse response = myReq.GetResponse();

        Stream responseStream = response.GetResponseStream();

        XmlTextReader reader = new XmlTextReader(responseStream);

        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Text)
                Console.WriteLine("{0}", reader.Value.Trim());
        }

        Console.ReadLine();

答案 2 :(得分:8)

internal string Get(string uri)
{
    using (WebResponse wr = WebRequest.Create(uri).GetResponse())
    {
        using (StreamReader sr = new StreamReader(wr.GetResponseStream()))
        {
            return sr.ReadToEnd();
        }
    }
}