HttpWebRequest Class - Process Exception Message

I

iana_kosio

Hi,

I am using HttpWebRequest class to communicate with remote server. In some cases the server would return 5xx status code which results in HttpWebRequest object throwing an exception. I, however, still need to access the response stream from the server as it contains information that I need. Any ideas how I can do that?

Thanks,
Konstantin

try
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://localhost/myUrl");
myRequest.Method = "GET";
WebResponse response = myRequest.GetResponse();
//If the server returns 5xx status code the next statement executed will be in the catch block
//Nevertheless, I still need the response stream from the server
Stream responseStream = response.GetResponseStream();
}
catch (System.Exception exc)
{
//Process exception
//How can I access the response stream from here?
}

**********************************************************************
Sent via Fuzzy Software @ http://www.fuzzysoftware.com/
Comprehensive, categorised, searchable collection of links to ASP & ASP.NET resources...
 
R

Rick Strahl [MVP]

Hi Konstantin,

By default WebRequest will throw an exception. You have to handle the
WebException and use the resulting ex.Response of it to read from to get the
full content from the server.

// *** Return the Response data
HttpWebResponse WebResponse = null;
try
{
WebResponse = (HttpWebResponse) loHttp.GetResponse();
}
catch(WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
WebResponse = (HttpWebResponse) ex.Response ;
}

Hope this helps,

+++ Rick ---

--

Rick Strahl
West Wind Technologies
www.west-wind.com
www.west-wind.com/weblog
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top