views:

246

answers:

2

If I have a raw HTTP response as a string:

HTTP/1.1 200 OK
Date: Tue, 11 May 2010 07:28:30 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=UTF-8
Server: gws
X-XSS-Protection: 1; mode=block
Connection: close

<!doctype html><html>...</html>

Is there an easy way I can parse it into an HttpListenerResponse object? Or at least some kind .NET object so I don't have to work with raw responses.

What I'm doing currently is extracting the header key/value pairs and setting them on the HttpListenerResponse. But some headers can't be set, and then I have to cut out the body of the response and write it to the OutputStream. But the body could be gzipped, or it could be an image, which I can't get to work yet. And some responses contain random characters everywhere, which looks like an encoding problem. It's a lot of trouble.

I'm getting a raw response because I'm using SOCKS to send an HTTP request. The program I'm working on is basically an HTTP proxy that can route requests through a SOCKS proxy, like Privoxy does.

+1  A: 

Maybe you want to take a look at the ResponseHeaders property of the Webclient:

WebClient wc = new WebClient();
wc.DownloadStringAsync(new Uri("http://www.foo.com"));

WebHeaderCollection myWebHeaderCollection = myWebClient.ResponseHeaders;

for (int i=0; i < myWebHeaderCollection.Count; i++)             
    Console.WriteLine ("\t" + myWebHeaderCollection.GetKey(i) + 
                       " = " + myWebHeaderCollection.Get(i));

Please tell me if that isnt what you were searching for.

Philip Daubmeier
Hmm just reread your question, and I think that may not help you if you just get a raw response and have to build up your response by hand...
Philip Daubmeier
Yeah, I'm currently using HttpListenerResponse.Headers.Set(key, value), which is the same thing. But thanks for your reply.
Ed
+1  A: 

Looks like there's no easy way to convert them. These articles helped:

http://stackoverflow.com/questions/506718/how-to-implement-custom-proxy-server

http://www.jeffcrossman.com/2009/08/27/using-httplistener-to-build-a-proxy

I ended up doing something very similar.

Ed