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

Sta*_*ker 42 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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ell 49

我只想使用异步方法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"));
Run Code Online (Sandbox Code Playgroud)

但要回答这个问题; 假设它是文本,类似于(注意您可能需要指定编码):

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


Fle*_*lea 13

如果响应来自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();
}
Run Code Online (Sandbox Code Playgroud)


foz*_*let 8

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