WebRequest 类

WebRequest 类

Sys.Net.WebRequest 类

 

 

提供用于发出 Web 请求的客户端脚本功能。

命名空间:Sys.Net

继承:

var wRequest = new Sys.Net.WebRequest();

名称

说明

Sys.Net.WebRequest webRequest 构造函数

初始化 WebRequest 类的新实例。

名称

说明

Sys.Net.WebRequest add_completed 方法

注册与 Web 请求实例关联的事件处理程序。

Sys.Net.WebRequest completed 方法

引发关联 Sys.Net.WebRequest 实例的完成事件。

Sys.Net.WebRequest.getResolvedUrl 方法

获取 Web 请求实例的解析后的 URL。

Sys.Net.WebRequest invoke 方法

为 Web 请求实例发出网络调用。

Sys.Net.WebRequest remove_completed 方法

移除与 Web 请求实例关联的事件处理程序。

Sys.Net.WebRequest body 属性

获取或设置 Web 请求的 HTTP 正文。

Sys.Net.WebRequest executor 属性

获取或设置关联 Web 请求实例的执行器。

Sys.Net.WebRequest headers 属性

获取 Web 请求的 HTTP 标头。

Sys.Net.WebRequest httpVerb 属性

获取或设置用于发出 Web 请求的 Web 请求 HTTP 谓词。

Sys.Net.WebRequest timeout 属性

获取或设置 Web 请求实例的超时值。

Sys.Net.WebRequest url 属性

获取或设置 Web 请求实例的 URL。

Sys.Net.WebRequest userContext 属性

获取或设置与 Web 请求实例关联的用户上下文。

异步通信层类使用 WebRequest 类发出 Web 请求。一般不在应用程序中直接使用此类型,而是通过使用代理方法,从浏览器调用 Web 服务方法或静态页方法。有关更多信息,请参见向客户端脚本公开 Web 服务

但是,可以在以下情况下创建和使用 WebRequest 实例:

  • 当您希望发出非简单 Web 服务方法调用的网络请求时。

  • 当您希望直接设置 HTTP 请求属性时。

  • 当您使用基于 Sys.Net.WebRequestExecutor 类的自定义执行器时。

下面的示例演示如何创建 WebRequest 类的实例来发出 GET Web 请求。该示例演示了一个网页以及用来与 WebRequest 类进行交互的客户端脚本。

Visual Basic
<%@ Page Language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html  >
    <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"  
                        οnclick="GetWebRequest()">GET</button>
                </td>
            </tr>
            <tr align="left">  
                <td>Request Body:</td>
                <td>
                    <button id="Button2"  
                        οnclick="PostWebRequest()">Body</button>
                </td>

            </tr>
            <tr align="left">
                <td>Request Timeout:</td>
                <td>
                    <button id="Button3"  
                        οnclick="WebRequestTimeout()">Timeout</button>
                </td>
            </tr> 
            <tr align="left">
                <td>Request Completed Handler:</td>
                <td>
                    <button id="Button4"  
                        οnclick="WebRequestCompleted()">Completed Handler</button>
                </td>
            </tr>

            <tr align="left">
                <td>Resolved Url:</td>
                <td>
                    <button id="Button5"  
                        οnclick="GetWebRequestResolvedUrl()">Resolved Url</button>
                </td>

            </tr>

            <tr align="left">
                <td>Request Executor:</td>
                <td>
                    <button id="Button6"  
                        οnclick="WebRequestExecutor()">Executor</button>
                </td>

            </tr>

            <tr align="left">
                <td>Request Header:</td>
                <td>
                    <button id="Button7"  
                        οnclick="WebRequestHeader()">Header</button>
                </td>

            </tr>

        </table>


        <hr />

        <div id="ResultId" style="background-color:Aqua;"></div>



    </body>

</html>

C#
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html  >
    <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"  
                        οnclick="GetWebRequest()">GET</button>
                </td>
            </tr>
            <tr align="left">  
                <td>Request Body:</td>
                <td>
                    <button id="Button2"  
                        οnclick="PostWebRequest()">Body</button>
                </td>

            </tr>
            <tr align="left">
                <td>Request Timeout:</td>
                <td>
                    <button id="Button3"  
                        οnclick="WebRequestTimeout()">Timeout</button>
                </td>
            </tr> 
            <tr align="left">
                <td>Request Completed Handler:</td>
                <td>
                    <button id="Button4"  
                        οnclick="WebRequestCompleted()">Completed Handler</button>
                </td>
            </tr>

            <tr align="left">
                <td>Resolved Url:</td>
                <td>
                    <button id="Button5"  
                        οnclick="GetWebRequestResolvedUrl()">Resolved Url</button>
                </td>

            </tr>

            <tr align="left">
                <td>Request Executor:</td>
                <td>
                    <button id="Button6"  
                        οnclick="WebRequestExecutor()">Executor</button>
                </td>

            </tr>

            <tr align="left">
                <td>Request Header:</td>
                <td>
                    <button id="Button7"  
                        οnclick="WebRequestHeader()">Header</button>
                </td>

            </tr>

        </table>


        <hr />

        <div id="ResultId" style="background-color:Aqua;"></div>



    </body>

</html>
PH
var getPage;
var postPage;
var displayElement;

function pageLoad()
{
    getPage = "getTarget.htm";
    postPage = "postTarget.aspx";
    displayElement = $get("ResultId");
}

// This function performs a GET Web request 
// to retrieve  information from the Url specified in 
// the query string. 
function GetWebRequest()
{
    alert("Performing Get Web request.");

    // Instantiate the WebRequest object.
    var wRequest =  new Sys.Net.WebRequest();

    // Set the request Url.  
    wRequest.set_url(getPage);  

    // Set the request verb.
    wRequest.set_httpVerb("GET");

    // Set user's context
    wRequest.set_userContext("user's context");

    // Set the web request completed event handler,
    // for processing return data.
    wRequest.add_completed(OnWebRequestCompleted);


    // Clear the results page element.
    displayElement.innerHTML = "";

    // Execute the request.
    wRequest.invoke();  

}

// This function performs a POST Web request
// to upload information to the resource 
// identified by the Url. 
function PostWebRequest()
{
    // Instantiate the WebRequest object.
    var wRequest =  new Sys.Net.WebRequest();

    // Set the request Url.  
    wRequest.set_url(postPage); 

    // Set the request verb.
    wRequest.set_httpVerb("POST");

    var body = "Message=Hello! Do you hear me?"
    wRequest.set_body(body);
    wRequest.get_headers()["Content-Length"] = body.length;


    // Set the web request completed event handler,
    // for processing return data.
    wRequest.add_completed(OnWebRequestCompleted);

    // Clear the results page element.
    displayElement.innerHTML = "";

    // Execute the request.
    wRequest.invoke();  
}

// This function adds and removes the 
// Web request completed event handler.
function WebRequestCompleted()
{
    // Instantiate the WebRequest.
    var wRequest =  new Sys.Net.WebRequest();

    // Set the request Url.  
    wRequest.set_url(getPage);  

    // Set the web request completed event handler,
    // for processing return data.
    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.");

    // Execute the request.
    wRequest.invoke();  
}

// This function gets the resolved Url 
// of the Web request instance.
function GetWebRequestResolvedUrl()
{
    // Instantiate the WebRequest.
    var wRequest =  new Sys.Net.WebRequest();

    // Set the request Url.  
    wRequest.set_url(getPage);  

    // Get the web request completed event handler.
    var resUrl = wRequest.getResolvedUrl();   
    alert("Resolved Url: " + resUrl);

    // Set the web request completed event handler,
    // for processing return data.
    wRequest.add_completed(OnWebRequestCompleted); 

    // Execute the request.
    wRequest.invoke();  

}


// This function gets and sets the 
// Web request time out.
function WebRequestTimeout()
{    
    // Instantiate the WebRequest.
    var wRequest =  new Sys.Net.WebRequest();

    // Set the request Url.  
    wRequest.set_url(getPage);  

    var defaultTimeout =  
        wRequest.get_timeout();

    // Set request timeout to 100 msec.
    wRequest.set_timeout(100);

    var newTimeout = 
        wRequest.get_timeout();

    alert("Default timeout: " + defaultTimeout);
    alert("New timeout: " + newTimeout);

    // Set the web request completed event handler,
    // for processing return data.
    wRequest.add_completed(OnWebRequestCompleted);   

    // Execute the request.
    wRequest.invoke();     
}


// This function sets the Web request
// executor, replacing the default one.
function WebRequestExecutor()
{    
    // Instantiate the WebRequest.
    var wRequest =  new Sys.Net.WebRequest();

    // Create the executor. In this case it is an
    // XMLHttpExecutor, equivalent to the default
    // executor. But, you can create a custom one.
    var executor = new Sys.Net.XMLHttpExecutor();

    // Set the executor, replacing the default one. 
    // In this case the executor is equivalent to the
    // default one.
    wRequest.set_executor(executor); 

    // Get the current executor       
    var executor =  
        wRequest.get_executor();

    alert("Response availabe: " + executor.get_responseAvailable())
}

 // This function sets an HTTP header for
 // the Web request.
 function WebRequestHeader() 
 {
       // Instantiate the WebRequest object.
    var wRequest =  new Sys.Net.WebRequest();

    // Set the request Url.  
    wRequest.set_url(postPage); 

    // Set the request verb.
    wRequest.set_httpVerb("POST");

    var body = "Message=Hello! Do you hear me?"
    wRequest.set_body(body);

    // Set the value of the HTTP header's "Content-Length".
    wRequest.get_headers()["Content-Length"] = body.length;

    // Set the web request completed event handler,
    // for processing return data.
    wRequest.add_completed(OnWebRequestCompletedHeader);

    // Clear the results page element.
    displayElement.innerHTML = "";

    // Execute the request.
    wRequest.invoke();  
}

// This the handler for the Web request completed event
// that is used to display return data.
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");
    }
}


// This the handler for the Web request completed event
// that is used to display header information.
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");

    }
}

// This function is used to display the Web request status.
function DisplayWebRequestStatus(executor)
{
     displayElement.innerHTML +=
     "Status: [" + 
     executor.get_statusCode() + " " + 
     executor.get_statusText() + "]" + "<br/>"
}

// This function is used to display Web request HTTP headers.
function DisplayWebRequestHeaders(executor)
{
    displayElement.innerHTML += 
        "Headers: ";
    displayElement.innerHTML += 
        executor.getAllResponseHeaders() + "<br/>";
 }

// This function is used to display the Web request body.
function DisplayWebRequestBody(executor)
{   
     displayElement.innerHTML += 
        "Body: ";
    if (document.all)
         displayElement.innerText += 
            executor.get_responseData();
    else
        // Firefox
         displayElement.textContent += 
            executor.get_responseData();
}

// This function is used to display the Web request message.
function DisplayInformation(message)
{
    // Clear the previous results.
     displayElement.innerHTML = "";
    // Display information.
    displayElement.innerHTML = "<br/>" + message;
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpClientWebRequest都是.NET Framework中用于发送HTTP请求的,但它们在设计和使用上有一些区别。 1. HttpClient是基于Task的异步模式设计的,它是.NET Framework 4及更高版本中引入的,提供了更为现代和简洁的API。它支持高级功能如连接复用、Pipelining等。 ```csharp using System.Net.Http; using System.Threading.Tasks; public class Example { public static async Task MakeRequestAsync() { using (HttpClient client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync("http://example.com"); // 处理响应... } } } ``` 2. WebRequest在.NET Framework早期版本中就已经存在,它是一个更传统的同步和异步API设计。尽管它可以通过WebRequest.Create方法创建请求,然后使用GetResponse方法或GetRequestStream方法来同步发送请求,或者使用BeginGetResponse和BeginGetRequestStream方法进行异步操作,但这些方法使用起来较为繁琐。 ```csharp using System.Net; using System.IO; public class Example { public static void MakeRequest() { WebRequest request = WebRequest.Create("http://example.com"); using (WebResponse response = request.GetResponse()) { using (Stream dataStream = response.GetResponseStream()) { // 读取响应流... } } } } ``` 3. HttpClient通常被认为在使用上更为方便,并且它更适合处理大量HTTP请求的场景,因为它在内部使用连接池来管理TCP连接,从而提高了性能。 4. WebRequest由于其历史较久,它提供了更多的可配置性,例如自定义代理设置、凭证和其他底层网络配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值