How to parse a raw HTTP response as HttpListenerResponse?

Edgar picture Edgar · May 11, 2010 · Viewed 7.6k times · Source

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.

Answer

Edgar picture Edgar · May 18, 2010

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

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.