[英]Titanium Web Proxy - Can't modify request body
我在使用 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\nTesting\n\n\n\n\n\n" 雖然它正確加載網站。
我已經嘗試為該網站添加阻止,就像它對谷歌一樣,它可以正常工作並阻止它。
有誰知道可能是什么問題? 我堅持了一段時間,所以任何幫助將不勝感激。
此示例中未實現內容更改,我只想將內容視為字符串,然后嘗試更改它。
如果我理解正確,您想在瀏覽器獲取響應之前修改從遠程服務器收到的響應。 掛鈎的正確位置是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 ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.