问题描述
我遇到了Titanium Web代理问题。我想要的是更改某些网站的内容,然后再将其加载到浏览器中。我已经实现了所有内容,并且工作正常,减去了不断变化的内容部分。这是代码的一部分:
public async Task OnRequest(object sender,SessionEventArgs e)
{
//Console.WriteLine(e.HttpClient.Request.Url);
// read request headers
var requestHeaders = e.HttpClient.Request.Headers;
var method = e.HttpClient.Request.Method.toupper();
if ((method == "POST" || method == "PUT" || method == "PATCH"))
{
// Get/Set request body bytes
byte[] bodyBytes = await e.GetRequestBody();
await Task.Run(() => e.SetRequestBody(bodyBytes));
// Get/Set request body as string
string bodyString = await e.GetRequestBodyAsstring();
await Task.Run(() => e.SetRequestBodyString(bodyString));
// store request
// so that you can find it from response handler
e.UserData = e.HttpClient.Request;
}
if(e.HttpClient.Request.RequestUri.AbsoluteUri.Contains("websiteiwanttochange"))
{
byte[] bodyBytes = await e.GetResponseBody();
e.SetRequestBody(bodyBytes);
string bodyString = await e.GetResponseBodyAsstring();
e.SetRequestBodyString(bodyString);
e.UserData = e.WebSession.Request;
Console.WriteLine("\n\n\n\n\n\n\nTesting\n\n\n\n\n\n");
Console.WriteLine(bodyBytes.ToString());
//Console.WriteLine(bodyString);
}
// To cancel a request with a custom HTML content
// Filter URL
if (e.HttpClient.Request.RequestUri.AbsoluteUri.Contains("google.com"))
{
e.Ok("<!DOCTYPE html>" +
"<html><body><h1>" +
"Website Blocked" +
"</h1>" +
"<p>Blocked by titanium web proxy.</p>" +
"</body>" +
"</html>");
}
// Redirect example
if (e.HttpClient.Request.RequestUri.AbsoluteUri.Contains("wikipedia.org"))
{
e.Redirect("https://www.paypal.com");
}
}
这几乎是我从Titanium Web代理Github中获得的示例。但是,尽管此代码可以正确加载网站,但它从未达到““ \ n \ n \ n \ n \ n \ n \ n \ nTesting \ n \ n \ n \ n \ n \ n”。
我已经尝试为该网站添加屏蔽功能,就像它适用于google一样,它可以正常运行并对其进行屏蔽。
有人知道这可能是什么问题吗?我对此坚持了一段时间,因此将不胜感激。
在此示例中未实现内容更改,我只想将内容显示为字符串,然后尝试对其进行更改。
解决方法
如果我理解正确,那么您想在浏览器获取到它之前修改从远程服务器收到的响应。挂接的正确位置是 OnBeforeResponse 事件。这是一个示例代码,我在其中更改了http://example.com的响应正文:
void Main()
{
var proxyServer = new ProxyServer(userTrustRootCertificate: false);
proxyServer.BeforeResponse += OnBeforeResponse;
var httpProxy = new ExplicitProxyEndPoint(IPAddress.Loopback,8080,decryptSsl: true);
proxyServer.AddEndPoint(httpProxy);
proxyServer.Start();
Console.ReadLine();
proxyServer.BeforeResponse -= OnBeforeResponse;
proxyServer.Stop();
}
public async Task OnBeforeResponse(object sender,SessionEventArgs ev)
{
var request = ev.HttpClient.Request;
var response = ev.HttpClient.Response;
if (String.Equals(ev.HttpClient.Request.RequestUri.Host,"www.example.com",StringComparison.OrdinalIgnoreCase)) {
var body = await ev.GetResponseBodyAsString();
body = body.Replace("<title>Example Domain</title>","<title>My Example Domain</title>");
ev.SetResponseBodyString(body);
}
}
并测试:
$ curl.exe --proxy http://localhost:8080 http://www.example.com
<!doctype html>
<html>
<head>
<title>My Example Domain</title>
... stripped ...