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
上使用异步方法-使用起来更容易:
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...
}
关于c# - 从WebResponse读取响应的最简单方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4533681/