我有这段代理代码,是从这篇文章中取得的,创建为一个HttpHandler。
public void ProcessRequest(HttpContext context)
{
string url = context.Request["url"];
string contentType = context.Request["type"];
// no buffering as we want to save memory
context.Response.Buffer = false;
// beging getting content
using (WebClient client = new WebClient())
{
// set content type if specified
if (!string.IsNullOrEmpty(contentType))
{
client.Headers.Add(HttpRequestHeader.ContentType, contentType);
}
client.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
client.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US");
client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows; U; Windows NT 6.0; " +
"en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
client.Headers.Add(HttpRequestHeader.Accept, "*/*");
// get that data
byte[] data = client.DownloadData(url);
if (!context.Response.IsClientConnected) return;
// deliver content type, encoding and length as it
// is received from the external url
context.Response.ContentType = client.ResponseHeaders["Content-Type"];
string contentEncoding = client.ResponseHeaders["Content-Encoding"];
string contentLength = client.ResponseHeaders["Content-Length"];
if (!string.IsNullOrEmpty(contentEncoding))
context.Response.AppendHeader(HttpRequestHeader.ContentEncoding.ToString(), contentEncoding);
if (!string.IsNullOrEmpty(contentLength))
context.Response.AppendHeader(HttpRequestHeader.ContentLength.ToString(), contentLength);
// transmit the exact bytes downloaded
context.Response.BinaryWrite(data);
}
}
我已将此 Http 模块映射为 IIS7 中的托管处理程序,并在我的纯 HTML 页面中使用 jQuery 调用代理并将结果放入 iframe。
$(document).ready(function() {
$.ajax({
type: "GET",
url: "a.RegularProxy",
data: { url: 'http://example.org/test.html', type: "text/html" },
dataType: "html",
success: function(data) {
$("iframe").contents().find('html body').html(data.toString());
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
当页面简单时,一切都运行良好。但是,如果页面被压缩(gzip、deflate),我需要找到一种在客户端上解压缩它而不是在代理服务器上解压缩的方法——代理服务器的功能是尽可能快。