HttpWebResponse send to web browser?
I am new to c# and am making a simple proxy to edit certain headers.
I have used HttpLisenter to get the request and then used HttpWebRequest and Response to edit, send and receiv开发者_运维百科e.
Now I need some help to send the edited response back to the web browser. Does anyone have any links or examples? Im stumped :)
Thanks
Here's a short example:
public void ProcessRequest(HttpContext context)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create([NEW_URL]);
request.Timeout = 1000 * 60 * 60;
request.Method = context.Request.HttpMethod;
if (request.Method.ToUpper() == "POST")
{
Stream sourceInputStream = context.Request.InputStream;
Stream targetOutputStream = request.GetRequestStream();
sourceInputStream.CopyTo(targetOutputStream);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
context.Response.ContentType = request.ContentType;
using (response)
{
Stream targetInputStream = response.GetResponseStream();
Stream sourceOutputStream = context.Response.OutputStream;
targetInputStream.CopyTo(sourceOutputStream);
}
}
This assume the following extension method is defined (I think using this makes the sample more readable):
public static void CopyTo(this Stream input, Stream output)
{
using (input)
using (output)
{
byte[] buffer = new byte[1024];
for (int amountRead = input.Read(buffer, 0, buffer.Length); amountRead > 0; amountRead = input.Read(buffer, 0, buffer.Length))
{
output.Write(buffer, 0, amountRead);
}
}
}
You could save the response to an html file and then start the browser with a command to open the file.
class Program
{
static int Main() {
WebRequest wr = HttpWebRequest.Create("http://google.com/");
HttpWebResponse wresp = (HttpWebResponse)wr.GetResponse();
string outFile = @"c:\tmp\google.html";
using (StreamReader sr = new StreamReader(wresp.GetResponseStream()))
{
using(StreamWriter sw = new StreamWriter(outFile, false)) {
sw.Write(sr.ReadToEnd());
}
}
BrowseFile(outFile);
return 0;
}
static void BrowseFile(string filePath)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
startInfo.Arguments = filePath;
Process.Start(startInfo);
}
}
Take a look at source code for existing proxy servers.
- Mini Proxy Server (c#)
- Web Proxy Server (c#)
精彩评论