最简单的方法来阅读WebResponse的响应
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对象,读取其内容的最简单方法是什么?
我只是简单地使用WebClient
上的asynchronous方法 – 更容易处理:
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"));
但要回答这个问题, 假设它是文本 ,就像(注意你可能需要指定编码):
using (var reader = new StreamReader(response.GetResponseStream())) { string result = reader.ReadToEnd(); // do something fun... }
如果响应来自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();
internal string Get(string uri) { using (WebResponse wr = WebRequest.Create(uri).GetResponse()) { using (StreamReader sr = new StreamReader(wr.GetResponseStream())) { return sr.ReadToEnd(); } } }