使用 AJAX 的 Sys.Net.WebRequest 从客户端请求网页
MS AJAX对JS进行了功能上的扩展,今天给大家讲述一下利用 Sys.Net.WebRequest 进行请求网页的一个例子.完整的程序代码:DoRequest.rar
新建网站,选择 ASP.NET AJAX-Enabled Web Site。
向网站中添加一个js文件 WebRequest.js。
添加三个全局变量:
getPage GET方法将要请求的URL。
postPage POST方法将要请求的URL。
displayElement 显示请求结果的HTML标签。
添加初始化函数:
下面是两个主要的请求函数,代码已经加入了注释,请读者仔细阅读。
利用Sys.Net.WebRequest()执行GET方法的函数:
利用Sys.Net.WebRequest();执行POST请求的函数:
WebRequest.js中最后完成的代码如下:
最后替换Default.aspx中的代码,用来测试我们的函数吧:
新建网站,选择 ASP.NET AJAX-Enabled Web Site。
向网站中添加一个js文件 WebRequest.js。
添加三个全局变量:
var getPage;
var postPage;
var displayElement;
var postPage;
var displayElement;
getPage GET方法将要请求的URL。
postPage POST方法将要请求的URL。
displayElement 显示请求结果的HTML标签。
添加初始化函数:
function pageLoad()
{
getPage = "getTarget.htm";
postPage = "postTarget.aspx";
displayElement = $get("ResultId");
}
在这个函数中指定了默认的请求页面和用来显示结果的HTML标签。{
getPage = "getTarget.htm";
postPage = "postTarget.aspx";
displayElement = $get("ResultId");
}
下面是两个主要的请求函数,代码已经加入了注释,请读者仔细阅读。
利用Sys.Net.WebRequest()执行GET方法的函数:
function GetWebRequest()
{
alert("Performing Get Web request.");
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(getPage);
// 设置请求方法.
wRequest.set_httpVerb("GET");
// Set user's context
wRequest.set_userContext("user's context");
// 添加完成请求事件
wRequest.add_completed(OnWebRequestCompleted);
// 清楚请求结果
displayElement.innerHTML = "";
// 执行请求
wRequest.invoke();
}
{
alert("Performing Get Web request.");
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(getPage);
// 设置请求方法.
wRequest.set_httpVerb("GET");
// Set user's context
wRequest.set_userContext("user's context");
// 添加完成请求事件
wRequest.add_completed(OnWebRequestCompleted);
// 清楚请求结果
displayElement.innerHTML = "";
// 执行请求
wRequest.invoke();
}
利用Sys.Net.WebRequest();执行POST请求的函数:
function PostWebRequest()
{
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(postPage);
// 设置请求方法.
wRequest.set_httpVerb("POST");
var body = "Message=Hello! Do you hear me?"
wRequest.set_body(body);
wRequest.get_headers()["Content-Length"] = body.length;
// 添加完成请求事件.
wRequest.add_completed(OnWebRequestCompleted);
// 清楚请求结果
displayElement.innerHTML = "";
// 执行请求
wRequest.invoke();
}
{
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(postPage);
// 设置请求方法.
wRequest.set_httpVerb("POST");
var body = "Message=Hello! Do you hear me?"
wRequest.set_body(body);
wRequest.get_headers()["Content-Length"] = body.length;
// 添加完成请求事件.
wRequest.add_completed(OnWebRequestCompleted);
// 清楚请求结果
displayElement.innerHTML = "";
// 执行请求
wRequest.invoke();
}
WebRequest.js中最后完成的代码如下:
// WebRequest.js
var getPage;
var postPage;
var displayElement;
function pageLoad()
{
getPage = "getTarget.htm";
postPage = "postTarget.aspx";
displayElement = $get("ResultId");
}
// 利用GET方法执行请求。
// 注意GET请求的参数包含在指定URL的查询参数中。
function GetWebRequest()
{
alert("Performing Get Web request.");
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(getPage);
// 设置请求方法.
wRequest.set_httpVerb("GET");
// Set user's context
wRequest.set_userContext("user's context");
// 添加完成请求事件
wRequest.add_completed(OnWebRequestCompleted);
// 清楚请求结果
displayElement.innerHTML = "";
// 执行请求
wRequest.invoke();
}
// 这个函数展示了如何设置请求的内容
//函数向指定的URL执行一个POST请求,将请求信息上传到了服务器
function PostWebRequest()
{
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(postPage);
// 设置请求方法.
wRequest.set_httpVerb("POST");
var body = "Message=Hello! Do you hear me?"
wRequest.set_body(body);
wRequest.get_headers()["Content-Length"] = body.length;
// 添加完成请求事件.
wRequest.add_completed(OnWebRequestCompleted);
// 清楚请求结果
displayElement.innerHTML = "";
// 执行请求
wRequest.invoke();
}
// 获取或设置请求完成事件
function WebRequestCompleted()
{
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(getPage);
// 添加完成请求事件.
wRequest.add_completed(OnWebRequestCompleted);
alert("Added Web request completed handler");
// Remove the web request completed event handler.
// Comment the following two lines if you want to
// use the handler.
wRequest.remove_completed(OnWebRequestCompleted);
alert("Removed handler; the Web request return is not processed.");
// 执行请求
wRequest.invoke();
}
// 获取请求的URL
function GetWebRequestResolvedUrl()
{
// Instantiate the WebRequest.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(getPage);
// 添加完成请求事件.
var resUrl = wRequest.getResolvedUrl();
alert("Resolved Url: " + resUrl);
// 添加完成请求事件.
wRequest.add_completed(OnWebRequestCompleted);
// 执行请求
wRequest.invoke();
}
//获取并设置请求的超时时间
function WebRequestTimeout()
{
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(getPage);
var defaultTimeout =
wRequest.get_timeout();
// 设置请求超时时间为 100 毫秒.
wRequest.set_timeout(100);
var newTimeout =
wRequest.get_timeout();
alert("Default timeout: " + defaultTimeout);
alert("New timeout: " + newTimeout);
// 添加完成请求事件.
wRequest.add_completed(OnWebRequestCompleted);
// 执行请求
wRequest.invoke();
}
//获取并设置请求实例.
function WebRequestExecutor()
{
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// Create the executor. In this case we just
// use the default executor. But, you can
// create a custom one.
var executor = new Sys.Net.XMLHttpExecutor();
// Set the executor.
wRequest.set_executor(executor);
// Get the current executor
var executor =
wRequest.get_executor();
alert("Response availabe: " + executor.get_responseAvailable())
}
// 获取并设置请求的头部
function WebRequestHeader()
{
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(postPage);
// 设置请求方法.
wRequest.set_httpVerb("POST");
var body = "Message=Hello! Do you hear me?"
wRequest.set_body(body);
// Set the header's length.
wRequest.get_headers()["Content-Length"] = body.length;
// 添加完成请求事件.
wRequest.add_completed(OnWebRequestCompletedHeader);
// 清楚请求结果
displayElement.innerHTML = "";
// 执行请求
wRequest.invoke();
}
// 请求完成的回掉函数
function OnWebRequestCompleted(executor, eventArgs)
{
if(executor.get_responseAvailable())
{
// Clear the previous results.
displayElement.innerHTML = "";
// Display Web request status.
DisplayWebRequestStatus(executor);
// Display Web request headers.
DisplayWebRequestHeaders(executor);
// Display Web request body.
DisplayWebRequestBody(executor);
}
else
{
if (executor.get_timedOut())
alert("Timed Out");
else
if (executor.get_aborted())
alert("Aborted");
}
}
// 显示请求头部信息的回调函数
function OnWebRequestCompletedHeader(executor, eventArgs)
{
if(executor.get_responseAvailable())
{
// Clear the previous results.
displayElement.innerHTML = "";
// Display Web request headers.
DisplayWebRequestHeaders(executor);
}
else
{
if (executor.get_timedOut())
alert("Timed Out");
else
if (executor.get_aborted())
alert("Aborted");
}
}
// 显示请求状态
function DisplayWebRequestStatus(executor)
{
displayElement.innerHTML +=
"Status: [" +
executor.get_statusCode() + " " +
executor.get_statusText() + "]" + "<br/>"
}
// 显示请求的头部
function DisplayWebRequestHeaders(executor)
{
displayElement.innerHTML +=
"Headers: ";
displayElement.innerHTML +=
executor.getAllResponseHeaders() + "<br/>";
}
// 显示请求的主体
function DisplayWebRequestBody(executor)
{
displayElement.innerHTML +=
"Body: ";
if (document.all)
displayElement.innerText +=
executor.get_responseData();
else
// Firefox
displayElement.textContent +=
executor.get_responseData();
}
function DisplayInformation(message)
{
// Clear the previous results.
displayElement.innerHTML = "";
// Display information.
displayElement.innerHTML = "<br/>" + message;
}
if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
var getPage;
var postPage;
var displayElement;
function pageLoad()
{
getPage = "getTarget.htm";
postPage = "postTarget.aspx";
displayElement = $get("ResultId");
}
// 利用GET方法执行请求。
// 注意GET请求的参数包含在指定URL的查询参数中。
function GetWebRequest()
{
alert("Performing Get Web request.");
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(getPage);
// 设置请求方法.
wRequest.set_httpVerb("GET");
// Set user's context
wRequest.set_userContext("user's context");
// 添加完成请求事件
wRequest.add_completed(OnWebRequestCompleted);
// 清楚请求结果
displayElement.innerHTML = "";
// 执行请求
wRequest.invoke();
}
// 这个函数展示了如何设置请求的内容
//函数向指定的URL执行一个POST请求,将请求信息上传到了服务器
function PostWebRequest()
{
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(postPage);
// 设置请求方法.
wRequest.set_httpVerb("POST");
var body = "Message=Hello! Do you hear me?"
wRequest.set_body(body);
wRequest.get_headers()["Content-Length"] = body.length;
// 添加完成请求事件.
wRequest.add_completed(OnWebRequestCompleted);
// 清楚请求结果
displayElement.innerHTML = "";
// 执行请求
wRequest.invoke();
}
// 获取或设置请求完成事件
function WebRequestCompleted()
{
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(getPage);
// 添加完成请求事件.
wRequest.add_completed(OnWebRequestCompleted);
alert("Added Web request completed handler");
// Remove the web request completed event handler.
// Comment the following two lines if you want to
// use the handler.
wRequest.remove_completed(OnWebRequestCompleted);
alert("Removed handler; the Web request return is not processed.");
// 执行请求
wRequest.invoke();
}
// 获取请求的URL
function GetWebRequestResolvedUrl()
{
// Instantiate the WebRequest.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(getPage);
// 添加完成请求事件.
var resUrl = wRequest.getResolvedUrl();
alert("Resolved Url: " + resUrl);
// 添加完成请求事件.
wRequest.add_completed(OnWebRequestCompleted);
// 执行请求
wRequest.invoke();
}
//获取并设置请求的超时时间
function WebRequestTimeout()
{
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(getPage);
var defaultTimeout =
wRequest.get_timeout();
// 设置请求超时时间为 100 毫秒.
wRequest.set_timeout(100);
var newTimeout =
wRequest.get_timeout();
alert("Default timeout: " + defaultTimeout);
alert("New timeout: " + newTimeout);
// 添加完成请求事件.
wRequest.add_completed(OnWebRequestCompleted);
// 执行请求
wRequest.invoke();
}
//获取并设置请求实例.
function WebRequestExecutor()
{
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// Create the executor. In this case we just
// use the default executor. But, you can
// create a custom one.
var executor = new Sys.Net.XMLHttpExecutor();
// Set the executor.
wRequest.set_executor(executor);
// Get the current executor
var executor =
wRequest.get_executor();
alert("Response availabe: " + executor.get_responseAvailable())
}
// 获取并设置请求的头部
function WebRequestHeader()
{
// 实例化 WebRequest 对象.
var wRequest = new Sys.Net.WebRequest();
// 设置请求的 URL.
wRequest.set_url(postPage);
// 设置请求方法.
wRequest.set_httpVerb("POST");
var body = "Message=Hello! Do you hear me?"
wRequest.set_body(body);
// Set the header's length.
wRequest.get_headers()["Content-Length"] = body.length;
// 添加完成请求事件.
wRequest.add_completed(OnWebRequestCompletedHeader);
// 清楚请求结果
displayElement.innerHTML = "";
// 执行请求
wRequest.invoke();
}
// 请求完成的回掉函数
function OnWebRequestCompleted(executor, eventArgs)
{
if(executor.get_responseAvailable())
{
// Clear the previous results.
displayElement.innerHTML = "";
// Display Web request status.
DisplayWebRequestStatus(executor);
// Display Web request headers.
DisplayWebRequestHeaders(executor);
// Display Web request body.
DisplayWebRequestBody(executor);
}
else
{
if (executor.get_timedOut())
alert("Timed Out");
else
if (executor.get_aborted())
alert("Aborted");
}
}
// 显示请求头部信息的回调函数
function OnWebRequestCompletedHeader(executor, eventArgs)
{
if(executor.get_responseAvailable())
{
// Clear the previous results.
displayElement.innerHTML = "";
// Display Web request headers.
DisplayWebRequestHeaders(executor);
}
else
{
if (executor.get_timedOut())
alert("Timed Out");
else
if (executor.get_aborted())
alert("Aborted");
}
}
// 显示请求状态
function DisplayWebRequestStatus(executor)
{
displayElement.innerHTML +=
"Status: [" +
executor.get_statusCode() + " " +
executor.get_statusText() + "]" + "<br/>"
}
// 显示请求的头部
function DisplayWebRequestHeaders(executor)
{
displayElement.innerHTML +=
"Headers: ";
displayElement.innerHTML +=
executor.getAllResponseHeaders() + "<br/>";
}
// 显示请求的主体
function DisplayWebRequestBody(executor)
{
displayElement.innerHTML +=
"Body: ";
if (document.all)
displayElement.innerText +=
executor.get_responseData();
else
// Firefox
displayElement.textContent +=
executor.get_responseData();
}
function DisplayInformation(message)
{
// Clear the previous results.
displayElement.innerHTML = "";
// Display information.
displayElement.innerHTML = "<br/>" + message;
}
if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
添加用以GET请求的页面getTarget.htm,代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>无标题页</title>
</head>
<body>
<p>
希望在以后的日子里大家多提些宝贵的意见,我会经常为大家写一些文章,有不足之处请多多指点。
☆聊ゾ聊☆
</p>
</body>
</html>
添加用以POST方法请求的测试页面postTarget.aspx:
<%@ Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Post Target</title>
<script language="C#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.Request.Form["Message"] != null)
LabelID.Text =
HttpContext.Current.Request.Form["Message"].ToString();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>WebRequestPost Target</h1>
<p>
<asp:Textbox id="LabelID" Text="test" runat="server"/>
</p>
Yes I hear you.
</div>
</form>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Post Target</title>
<script language="C#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.Request.Form["Message"] != null)
LabelID.Text =
HttpContext.Current.Request.Form["Message"].ToString();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>WebRequestPost Target</h1>
<p>
<asp:Textbox id="LabelID" Text="test" runat="server"/>
</p>
Yes I hear you.
</div>
</form>
</body>
</html>
最后替换Default.aspx中的代码,用来测试我们的函数吧:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title> Using WebRequest </title>
<style type="text/css">
body { font: 11pt Trebuchet MS;
font-color: #000000;
padding-top: 72px;
text-align: center }
.text { font: 8pt Trebuchet MS }
</style>
</head>
<body>
<h2>Using WebRequest</h2>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManagerId">
<Scripts>
<asp:ScriptReference Path="WebRequest.js" />
</Scripts>
</asp:ScriptManager>
</form>
<table>
<tr align="left">
<td>Make GET Request:</td>
<td>
<button id="Button1"
onclick="GetWebRequest()">GET</button>
</td>
</tr>
<tr align="left">
<td>Request Body:</td>
<td>
<button id="Button2"
onclick="PostWebRequest()">Body</button>
</td>
</tr>
<tr align="left">
<td>Request Timeout:</td>
<td>
<button id="Button3"
onclick="WebRequestTimeout()">Timeout</button>
</td>
</tr>
<tr align="left">
<td>Request Completed Handler:</td>
<td>
<button id="Button4"
onclick="WebRequestCompleted()">Completed Handler</button>
</td>
</tr>
<tr align="left">
<td>Resolved Url:</td>
<td>
<button id="Button5"
onclick="GetWebRequestResolvedUrl()">Resolved Url</button>
</td>
</tr>
<tr align="left">
<td>Request Executor:</td>
<td>
<button id="Button6"
onclick="WebRequestExecutor()">Executor</button>
</td>
</tr>
<tr align="left">
<td>Request Header:</td>
<td>
<button id="Button7"
onclick="WebRequestHeader()">Header</button>
</td>
</tr>
</table>
<hr />
<div id="ResultId" style="background-color:Aqua;"></div>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title> Using WebRequest </title>
<style type="text/css">
body { font: 11pt Trebuchet MS;
font-color: #000000;
padding-top: 72px;
text-align: center }
.text { font: 8pt Trebuchet MS }
</style>
</head>
<body>
<h2>Using WebRequest</h2>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="ScriptManagerId">
<Scripts>
<asp:ScriptReference Path="WebRequest.js" />
</Scripts>
</asp:ScriptManager>
</form>
<table>
<tr align="left">
<td>Make GET Request:</td>
<td>
<button id="Button1"
onclick="GetWebRequest()">GET</button>
</td>
</tr>
<tr align="left">
<td>Request Body:</td>
<td>
<button id="Button2"
onclick="PostWebRequest()">Body</button>
</td>
</tr>
<tr align="left">
<td>Request Timeout:</td>
<td>
<button id="Button3"
onclick="WebRequestTimeout()">Timeout</button>
</td>
</tr>
<tr align="left">
<td>Request Completed Handler:</td>
<td>
<button id="Button4"
onclick="WebRequestCompleted()">Completed Handler</button>
</td>
</tr>
<tr align="left">
<td>Resolved Url:</td>
<td>
<button id="Button5"
onclick="GetWebRequestResolvedUrl()">Resolved Url</button>
</td>
</tr>
<tr align="left">
<td>Request Executor:</td>
<td>
<button id="Button6"
onclick="WebRequestExecutor()">Executor</button>
</td>
</tr>
<tr align="left">
<td>Request Header:</td>
<td>
<button id="Button7"
onclick="WebRequestHeader()">Header</button>
</td>
</tr>
</table>
<hr />
<div id="ResultId" style="background-color:Aqua;"></div>
</body>
</html>