如何通过HTTP获得响应

时间:2013-04-23 11:17:41

标签: c# http http-post httprequest httpresponse

我正在发送HTTP请求。我需要保存对该请求的HTTP响应。

这是请求网址:http://notify.test.com/gateway.do?service=notify_verify&partner=2088&notify_id=abcdefghijklmnopqrst

我试过的代码如下:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://notify.test.com/gateway.do?service=notify_verify&partner=2088&notify_id=abcdefghijklmnopqrst");
        request.Proxy = WebProxy.GetDefaultProxy();
        request.Proxy.Credentials = CredentialCache.DefaultCredentials;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream resStream = response.GetResponseStream();

回复将为True或False。我怎么能保存呢?

3 个答案:

答案 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.Streamhere

答案 2 :(得分:1)

using(var resStream = response.GetResponseStream())
using(var reader = new StreamReader(resStream))
{
    var responseText = reader.ReadToEnd();
}