我正在发送HTTP请求。我需要保存对该请求的HTTP响应。
这是请求网址:http://notify.test.com/gateway.do?service=notify_verify&partner=2088¬ify_id=abcdefghijklmnopqrst
我试过的代码如下:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://notify.test.com/gateway.do?service=notify_verify&partner=2088¬ify_id=abcdefghijklmnopqrst");
request.Proxy = WebProxy.GetDefaultProxy();
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
回复将为True或False。我怎么能保存呢?
答案 0 :(得分:2)
如果您的要求很简单,WebClient
有很长的路要走:
string result;
using(var client = new WebClient()) {
client.Proxy = ...
result = client.DownloadString(uri);
}
另请参阅:DownloadData
等。
答案 1 :(得分:1)
您从System.IO.Stream
获得GetResponseStream()
,Stream
为您提供了您可以阅读的Read
方法
using(Stream resStream = response.GetResponseStream()){ //release Stream after use
if(resStream.CanRead){
byte[] buffer = new byte[resStream.Length]; // or whatever
if(resStream.Read(buffer, 0, resStream.Length) == 0)
{
// end of Stream
}
else{
//data received, work on buffer
}
}
}
System.IO.Stream
见here。
答案 2 :(得分:1)
using(var resStream = response.GetResponseStream())
using(var reader = new StreamReader(resStream))
{
var responseText = reader.ReadToEnd();
}