HttpWebRequest.GetResponse 方法

定义

返回来自 Internet 资源的响应。Returns a response from an Internet resource.

public:
 override System::Net::WebResponse ^ GetResponse();
public override System.Net.WebResponse GetResponse ();
override this.GetResponse : unit -> System.Net.WebResponse
Public Overrides Function GetResponse () As WebResponse

返回

包含来自 Internet 资源的响应的 WebResponseA WebResponse that contains the response from the Internet resource.

异常

该流已由对 BeginGetResponse(AsyncCallback, Object) 的上一个调用使用。The stream is already in use by a previous call to BeginGetResponse(AsyncCallback, Object).

-or- TransferEncoding 设置为一个值,且 SendChunkedfalseTransferEncoding is set to a value and SendChunked is false.

Method 为 GET 或 HEAD,并且或者 ContentLength 大于或等于零,或者 SendChunkedtrueMethod is GET or HEAD, and either ContentLength is greater or equal to zero or SendChunked is true.

-or- KeepAlivetrueAllowWriteStreamBufferingfalseContentLength 为 -1,SendChunkedfalseMethod 为 POST 或 PUT。KeepAlive is true, AllowWriteStreamBuffering is false, ContentLength is -1, SendChunked is false, and Method is POST or PUT.

-or- HttpWebRequest 具有实体,但不用调用 GetResponse() 方法调用 GetRequestStream() 方法。The HttpWebRequest has an entity body but the GetResponse() method is called without calling the GetRequestStream() method.

-or- ContentLength 大于零,但应用程序不会写入所有承诺的数据。The ContentLength is greater than zero, but the application does not write all of the promised data.

请求缓存验证程序指示对此请求的响应可从缓存中提供;但是,此请求包含要发送到服务器的数据。The request cache validator indicated that the response for this request can be served from the cache; however, this request includes data to be sent to the server. 发送数据的请求不得使用缓存。Requests that send data must not use the cache. 如果你正在使用错误实现的自定义缓存验证程序,则会发生此异常。This exception can occur if you are using a custom cache validator that is incorrectly implemented.

之前已调用 Abort()Abort() was previously called.

-or- 请求的超时期限到期。The time-out period for the request expired.

-or- 处理请求时出错。An error occurred while processing the request.

示例

下面的代码示例获取请求的响应。The following code example gets the response for a request.

#using <System.dll>

using namespace System;
using namespace System::Net;
using namespace System::Text;
using namespace System::IO;

// Specify the URL to receive the request.
int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();
   HttpWebRequest^ request = dynamic_cast<HttpWebRequest^>(WebRequest::Create( args[ 1 ] ));
   
   // Set some reasonable limits on resources used by this request
   request->MaximumAutomaticRedirections = 4;
   request->MaximumResponseHeadersLength = 4;
   
   // Set credentials to use for this request.
   request->Credentials = CredentialCache::DefaultCredentials;
   HttpWebResponse^ response = dynamic_cast<HttpWebResponse^>(request->GetResponse());
   Console::WriteLine( "Content length is {0}", response->ContentLength );
   Console::WriteLine( "Content type is {0}", response->ContentType );
   
   // Get the stream associated with the response.
   Stream^ receiveStream = response->GetResponseStream();
   
   // Pipes the stream to a higher level stream reader with the required encoding format. 
   StreamReader^ readStream = gcnew StreamReader( receiveStream,Encoding::UTF8 );
   Console::WriteLine( "Response stream received." );
   Console::WriteLine( readStream->ReadToEnd() );
   response->Close();
   readStream->Close();
}

/*
The output from this example will vary depending on the value passed into Main 
but will be similar to the following:

Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/
using System;
using System.Net;
using System.Text;
using System.IO;


    public class Test
    {
        // Specify the URL to receive the request.
        public static void Main (string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

            Console.WriteLine ("Content length is {0}", response.ContentLength);
            Console.WriteLine ("Content type is {0}", response.ContentType);
             
            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream ();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

            Console.WriteLine ("Response stream received.");
            Console.WriteLine (readStream.ReadToEnd ());
            response.Close ();
            readStream.Close ();
        }
    }

/*
The output from this example will vary depending on the value passed into Main 
but will be similar to the following:

Content length is 1542
Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/
Imports System.Net
Imports System.Text
Imports System.IO


    Public Class Test

        ' Specify the URL to receive the request.
        Public Shared Sub Main(ByVal args() As String)
        Dim request As HttpWebRequest = CType(WebRequest.Create(args(0)), HttpWebRequest)


        ' Set some reasonable limits on resources used by this request
        request.MaximumAutomaticRedirections = 4
        request.MaximumResponseHeadersLength = 4

        ' Set credentials to use for this request.
        request.Credentials = CredentialCache.DefaultCredentials

        Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)

        Console.WriteLine("Content length is {0}", response.ContentLength)
        Console.WriteLine("Content type is {0}", response.ContentType)

        ' Get the stream associated with the response.
        Dim receiveStream As Stream = response.GetResponseStream()

        ' Pipes the stream to a higher level stream reader with the required encoding format. 
        Dim readStream As New StreamReader(receiveStream, Encoding.UTF8)

        Console.WriteLine("Response stream received.")
        Console.WriteLine(readStream.ReadToEnd())
        response.Close()
        readStream.Close()
    End Sub
End Class
'
'The output from this example will vary depending on the value passed into Main 
'but will be similar to the following:
'
'Content length is 1542
'Content type is text/html; charset=utf-8
'Response stream received.
'...
'
'

注解

GetResponse 方法返回包含来自 Internet 资源的响应的 WebResponse 对象。The GetResponse method returns a WebResponse object that contains the response from the Internet resource. 返回的实际实例是一个 HttpWebResponse,可转换到该类以访问特定于 HTTP 的属性。The actual instance returned is an HttpWebResponse, and can be typecast to that class to access HTTP-specific properties.

如果在 HttpWebRequest 类上设置的属性冲突,则在若干情况下会引发 ProtocolViolationExceptionA ProtocolViolationException is thrown in several cases when the properties set on the HttpWebRequest class are conflicting. 如果应用程序将 ContentLength 属性和 SendChunked 属性设置为 true,然后发送 HTTP GET 请求,则会发生此异常。This exception occurs if an application sets the ContentLength property and the SendChunked property to true, and then sends an HTTP GET request. 如果应用程序尝试将分块发送到仅支持 HTTP 1.0 协议(不支持此协议)的服务器,则会发生此异常。This exception occurs if an application tries to send chunked to a server that only supports HTTP 1.0 protocol, where this is not supported. 如果应用程序尝试在不设置 ContentLength 属性的情况下发送数据,false SendChunked 或在停用连接上禁用了缓冲并在 keepalive 连接上(KeepAlive 属性为 true),则会发生此异常.This exception occurs if an application tries to send data without setting the ContentLength property or the SendChunked is false when buffering is disabled and on a keepalive connection (the KeepAlive property is true).

注意

必须调用 Close 方法来关闭流并释放连接。You must call the Close method to close the stream and release the connection. 否则,可能会导致应用程序无法连接。Failure to do so may cause your application to run out of connections.

使用 POST 方法时,必须获取请求流,写入要发布的数据,并关闭流。When using the POST method, you must get the request stream, write the data to be posted, and close the stream. 此方法阻止等待内容发布;如果没有设置任何超时,且未提供内容,则调用线程会无限期阻止。This method blocks waiting for content to post; if there is no time-out set and you do not provide content, the calling thread blocks indefinitely.

备注

多次调用 GetResponse 返回相同的响应对象;不会重新颁发请求。Multiple calls to GetResponse return the same response object; the request is not reissued.

备注

应用程序不能为特定请求混合使用同步和异步方法。Your application cannot mix synchronous and asynchronous methods for a particular request. 如果调用 GetRequestStream 方法,则必须使用 GetResponse 方法来检索响应。If you call the GetRequestStream method, you must use the GetResponse method to retrieve the response.

备注

如果引发了 WebException,请使用异常的 ResponseStatus 属性来确定来自服务器的响应。If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息,请参阅.NET Framework 中的网络跟踪For more information, see Network Tracing in the .NET Framework.

备注

出于安全考虑,默认情况下会禁用 cookie。For security reasons, cookies are disabled by default. 如果要使用 cookie,请使用 CookieContainer 属性启用 cookie。If you wish to use cookies, use the CookieContainer property to enable cookies.

适用于

另请参阅