本文由机器翻译。若要查看英语原文,请勾选“英语”复选框。 也可将鼠标指针移到文本上,在弹出窗口中显示英语原文。
翻译
英语

HttpWebRequest.BeginGetResponse 方法 (AsyncCallback, Object)

 

开始对 Internet 资源的异步请求。

命名空间:   System.Net
程序集:  System(位于 System.dll)

[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public override IAsyncResult BeginGetResponse(
	AsyncCallback callback,
	object state
)

参数

callback
Type: System.AsyncCallback

AsyncCallback 委托

state
Type: System.Object

此请求的状态对象。

返回值

Type: System.IAsyncResult

引用响应的异步请求的 IAsyncResult

Exception Condition
InvalidOperationException

BeginGetResponse 的上一个调用已使用该流

- 或 -

TransferEncoding 设置为一个值,且 SendChunkedfalse

- 或 -

线程池中线程即将耗尽。

ProtocolViolationException

Method 为 GET 或 HEAD,并且 ContentLength 大于零或 SendChunkedtrue

- 或 -

KeepAlivetrueAllowWriteStreamBufferingfalse,并且 ContentLength 为 -1 或者 SendChunkedfalse,且 Method 为 POST 或 PUT。

- 或 -

HttpWebRequest 具有实体主体,但在不调用 BeginGetRequestStream 方法的情况下调用了 BeginGetResponse 方法。

- 或 -

ContentLength 大于零,但应用程序不会写入所有承诺的数据。

WebException

之前已调用 Abort

BeginGetResponse 方法从 Internet 资源开始对响应的异步请求。 异步回调方法使用 EndGetResponse 方法返回的实际 WebResponse

一个 ProtocolViolationException 时设置的属性,在某些情况下引发 HttpWebRequest 类的冲突。 如果应用程序设置,则会发生此异常 ContentLength 属性和 SendChunked 属性设置为 true, ,然后将发送 HTTP GET 请求。 如果应用程序尝试向发送到的服务器上仅支持 HTTP 1.0 协议分块请求不支持这样做,会发生此异常。 如果应用程序尝试发送数据,但不包括设置,则会发生此异常 ContentLength 属性或 SendChunkedfalse 禁用缓冲和 keepalive 连接上 ( KeepAlive 属性是 true).

如果 WebException 是抛出,使用 ResponseStatus 异常以确定服务器的响应的属性。

BeginGetResponse 方法需要执行一些同步设置任务完成 (DNS 解析、 代理服务器检测和 TCP 套接字连接,例如),然后该方法成为异步。 结果是,此方法应永远不会调用用户界面 (UI) 线程上因为它可能需要相当长的时间 (最多几分钟时间,具体取决于网络设置) 来完成初始同步设置的任务之前的错误将引发异常或该方法成功。

若要了解有关线程池的详细信息,请参阅 The Managed Thread Pool

System_CAPS_note说明

您的应用程序不能混用的特定请求的同步和异步方法。 如果调用 BeginGetRequestStream 方法,则必须使用 BeginGetResponse 方法以检索响应。

System_CAPS_note说明

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。 有关详细信息,请参阅.NET Framework 中的网络跟踪

下面的代码示例使用 BeginGetResponse 方法来执行对 Internet 资源的异步请求。

System_CAPS_note说明

在异步请求的情况下它是客户端应用程序,来实现其自己的超时机制的责任。 下面的代码示例演示如何执行此操作。

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;


public class RequestState
{
  // This class stores the State of the request.
  const int BUFFER_SIZE = 1024;
  public StringBuilder requestData;
  public byte[] BufferRead;
  public HttpWebRequest request;
  public HttpWebResponse response;
  public Stream streamResponse;
  public RequestState()
  {
    BufferRead = new byte[BUFFER_SIZE];
    requestData = new StringBuilder("");
    request = null;
    streamResponse = null;
  }
}

class HttpWebRequest_BeginGetResponse
{
  public static ManualResetEvent allDone= new ManualResetEvent(false);
  const int BUFFER_SIZE = 1024;
  const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout

  // Abort the request if the timer fires.
  private static void TimeoutCallback(object state, bool timedOut) { 
      if (timedOut) {
          HttpWebRequest request = state as HttpWebRequest;
          if (request != null) {
              request.Abort();
          }
      }
  }

  static void Main()
  {  

    try
    {
      // Create a HttpWebrequest object to the desired URL. 
      HttpWebRequest myHttpWebRequest= (HttpWebRequest)WebRequest.Create("http://www.contoso.com");


  /**
    * If you are behind a firewall and you do not have your browser proxy setup
    * you need to use the following proxy creation code.

      // Create a proxy object.
      WebProxy myProxy = new WebProxy();

      // Associate a new Uri object to the _wProxy object, using the proxy address
      // selected by the user.
      myProxy.Address = new Uri("http://myproxy");


      // Finally, initialize the Web request object proxy property with the _wProxy
      // object.
      myHttpWebRequest.Proxy=myProxy;
    ***/

      // Create an instance of the RequestState and assign the previous myHttpWebRequest
      // object to its request field.  
      RequestState myRequestState = new RequestState();  
      myRequestState.request = myHttpWebRequest;


      // Start the asynchronous request.
      IAsyncResult result=
        (IAsyncResult) myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback),myRequestState);

      // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
      ThreadPool.RegisterWaitForSingleObject (result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), myHttpWebRequest, DefaultTimeout, true);

      // The response came in the allowed time. The work processing will happen in the 
      // callback function.
      allDone.WaitOne();

      // Release the HttpWebResponse resource.
      myRequestState.response.Close();
    }
    catch(WebException e)
    {
      Console.WriteLine("\nMain Exception raised!");
      Console.WriteLine("\nMessage:{0}",e.Message);
      Console.WriteLine("\nStatus:{0}",e.Status);
      Console.WriteLine("Press any key to continue..........");
    }
    catch(Exception e)
    {
      Console.WriteLine("\nMain Exception raised!");
      Console.WriteLine("Source :{0} " , e.Source);
      Console.WriteLine("Message :{0} " , e.Message);
      Console.WriteLine("Press any key to continue..........");
      Console.Read();
    }
  }
  private static void RespCallback(IAsyncResult asynchronousResult)
  {  
    try
    {
      // State of request is asynchronous.
      RequestState myRequestState=(RequestState) asynchronousResult.AsyncState;
      HttpWebRequest  myHttpWebRequest=myRequestState.request;
      myRequestState.response = (HttpWebResponse) myHttpWebRequest.EndGetResponse(asynchronousResult);

      // Read the response into a Stream object.
      Stream responseStream = myRequestState.response.GetResponseStream();
      myRequestState.streamResponse=responseStream;

      // Begin the Reading of the contents of the HTML page and print it to the console.
      IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
      return;
    }
    catch(WebException e)
    {
      Console.WriteLine("\nRespCallback Exception raised!");
      Console.WriteLine("\nMessage:{0}",e.Message);
      Console.WriteLine("\nStatus:{0}",e.Status);
    }
    allDone.Set();
  }
  private static  void ReadCallBack(IAsyncResult asyncResult)
  {
    try
    {

    RequestState myRequestState = (RequestState)asyncResult.AsyncState;
    Stream responseStream = myRequestState.streamResponse;
    int read = responseStream.EndRead( asyncResult );
    // Read the HTML page and then print it to the console.
    if (read > 0)
    {
      myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read));
      IAsyncResult asynchronousResult = responseStream.BeginRead( myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
      return;
    }
    else
    {
      Console.WriteLine("\nThe contents of the Html page are : ");
      if(myRequestState.requestData.Length>1)
      {
        string stringContent;
        stringContent = myRequestState.requestData.ToString();
        Console.WriteLine(stringContent);
      }
      Console.WriteLine("Press any key to continue..........");
      Console.ReadLine();

      responseStream.Close();
    }

    }
    catch(WebException e)
    {
      Console.WriteLine("\nReadCallBack Exception raised!");
      Console.WriteLine("\nMessage:{0}",e.Message);
      Console.WriteLine("\nStatus:{0}",e.Status);
    }
    allDone.Set();

  }

通用 Windows 平台
自 8 起可用
.NET Framework
自 1.1 起可用
可移植类库
可移植 .NET 平台 中受支持
Silverlight
自 2.0 起可用
Windows Phone Silverlight
自 7.0 起可用
Windows Phone
自 8.1 起可用
返回页首
显示: