Skip to content

Instantly share code, notes, and snippets.

@kthompson
Created January 13, 2012 01:33
Show Gist options
  • Save kthompson/1604161 to your computer and use it in GitHub Desktop.
Save kthompson/1604161 to your computer and use it in GitHub Desktop.
eric's code refactored
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
}
public static string Test(WebRequest request)
{
try
{
var response = (HttpWebResponse)request.GetResponse();
return ReadResponse(response);
}
catch (WebException ex)
{
if (ex.Response != null)
System.Diagnostics.Trace.WriteLine(ReadResponse(ex.Response));
if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
{
WebResponse r = ex.Response;
System.Diagnostics.Trace.WriteLine("Status: " + ex.Status);
HttpWebResponse resp = (HttpWebResponse)r;
switch (resp.StatusCode)
{
case HttpStatusCode.NotFound:
return null;
//etc, etc, you can add all the codes here and rethrow or do something useful :)
default:
//much testing it seems that the WebResponse generated for the
//exception does not contain the body (yet preserves the content length field, as
//a teaser i suppose ;)). So unfortunately this part will always return null.
System.Diagnostics.Trace.WriteLine("StatusCode: " + resp.StatusCode);
return ReadResponse(resp);
}
}
}
return null;
}
private static string ReadResponse(WebResponse resp)
{
using (Stream stream = resp.GetResponseStream())
{
return new StreamReader(stream).ReadToEnd();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment