简体   繁体   中英

How to get the response over HTTP

I am sending HTTP request. I need to save the HTTP response to that request.

This is the request URL : http://notify.test.com/gateway.do?service=notify_verify&partner=2088&notify_id=abcdefghijklmnopqrst

Code I tried is below:

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();

The response will be True or False. how can I save that?

If your requirements are simple, WebClient goes a long way:

string result;
using(var client = new WebClient()) {
    client.Proxy = ...
    result = client.DownloadString(uri);
}

See also: DownloadData etc.

You acquire a System.IO.Stream from GetResponseStream() , the Stream offers you the Read method you can read on

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
        }
    }
}

See here for System.IO.Stream .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM