我是c#的新手,我正在制作一个简单的代理来编辑某些标题。
我使用HttpLisenter获取请求,然后使用HttpWebRequest和Response进行编辑,发送和接收。
现在我需要一些帮助才能将已编辑的响应发送回Web浏览器。有没有人有任何链接或例子?我很难过:)
由于
答案 0 :(得分:3)
这是一个简短的例子:
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);
}
}
这假设定义了以下扩展方法(我认为使用它会使示例更具可读性):
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);
}
}
}
答案 1 :(得分:0)
您可以将响应保存到html文件,然后使用命令启动浏览器以打开文件。
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);
}
}
答案 2 :(得分:0)
查看现有代理服务器的源代码。