WebRequest支持不同的浏览器对象,可以在底层使用不同的XMLHttpRquest方式调用Web服务。
Time.aspx
<%@ Page Language="C#" %> <script runat="server"> protected override void OnLoad(EventArgs e) { base.OnLoad(e); Response.Write(DateTime.Now.ToUniversalTime()); } </script>
CallTimeWebRequest.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CallTimeWebRequest.aspx.cs" Inherits="Chap9Project.CallTimeWebRequest" %> <!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 runat="server"> <title></title> <script type="text/javascript"> function pageLoad() { var webRequest = new Sys.Net.WebRequest(); webRequest.set_url("Time.aspx"); webRequest.add_completed(completedHandler); webRequest.invoke(); } function completedHandler(result, eventArgs) { if (result.get_responseAvailable()) { alert(result.get_statusText()); alert(result.get_responseData()); } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> </div> </form> </body> </html>
WebRequest默认请求方式是GET,可以使用POST上传数据。
EchoABC.aspx
<%@ Page Language="C#" %> <script runat="server"> protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (Request.Form["abc"] != null) { Response.Write(Server.HtmlEncode(Request.Form["abc"])); } } </script>
SetVerb.aspx
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>NetWorking</title> <script type="text/javascript"> function pageLoad() { var webRequest = new Sys.Net.WebRequest(); webRequest.set_url("EchoABC.aspx"); webRequest.set_httpVerb("POST"); webRequest.set_body("abc=123"); webRequest.add_completed(completedHandler); webRequest.invoke(); } function completedHandler(result, eventArgs) { if (result.get_responseAvailable()) { alert(result.get_statusText()); alert(result.get_responseData()); } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> </div> </form> </body> </html>
WebRequest对象还可以设置超时限制。
TimeOut.aspx
...
function pageLoad(){
...
webRequest.set_timeout(5000);
}
function completedHandler(result, eventArgs){
if(result.get_timeOut()){
...
}
if(result.get_responseAvailable()) {
...
}
}
WebRequset传递额外数据
UserContent.aspx
...
function pageLoad(){
...
webRequest.set_userContext('send this data to the callback');
}
function completedHandler(result, eventArgs){
if(result.get_responseAvailable()) {
var userContext = result.get_webRequest().get_userContext();
}
}
WebRequest获取即将发出的请求的完整的URL
WebRequest.getResolvedUrl()