HttpWebRequest.GetResponse 方法


GetResponse 方法返回包含來自 Internet 資源的響應的 WebResponse 對象。 實際返回的實例是 HttpWebResponse,並且能夠轉換為訪問 HTTP 特定的屬性的類。

 

在一些情況下,當對 HttpWebRequest 類設置的屬性發生沖突時將引發 ProtocolViolationException。 如果應用程序將 ContentLength 屬性和 SendChunked 屬性設置為true,然后發送 HTTP GET 請求,則會引發該異常。 如果應用程序嘗試向僅支持 HTTP 1.0 協議而不支持分塊請求的服務器發送分塊請求,則會引發該異常。 如果應用程序未設置 ContentLength 屬性就嘗試發送數據,或者在 keepalive 連接(KeepAlive 屬性為 true)上禁用緩沖時 SendChunked 為 false,則會引發該異常

 

警告

必須調用 Close 方法關閉該流並釋放連接。 如果未能做到這一點,可能導致應用程序用完連接。

使用 POST 方法時,必須獲取請求流,寫入要發送的數據,然后關閉請求流。 此方法阻塞以等待發送的內容;如果沒有超時設置並且您沒有提供內容,調用線程將無限期地阻塞。

 

說明

多次調用 GetResponse 會返回相同的響應對象;該請求不會重新發出。

說明

應用程序不能對特定請求混合使用同步和異步方法。 如果調用 GetRequestStream 方法,則必須使用 GetResponse 方法檢索響應。

 

 

說明

如果引發 WebException,請使用該異常的 Response 和 Status 屬性確定服務器的響應。

說明

當應用程序中啟用了網絡跟蹤時,此成員將輸出跟蹤信息。 有關詳細信息,請參閱 網絡跟蹤

說明

為安全起見,默認情況下禁用 Cookie。 如果您希望使用 Cookie,請使用 CookieContainer 屬性啟用 Cookie。

 

 1 using System;
 2 using System.Net;
 3 using System.Text;
 4 using System.IO;
 5 
 6 
 7     public class Test
 8     {
 9         // Specify the URL to receive the request.
10         public static void Main (string[] args)
11         {
12             HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);
13 
14             // Set some reasonable limits on resources used by this request
15             request.MaximumAutomaticRedirections = 4;
16             request.MaximumResponseHeadersLength = 4;
17             // Set credentials to use for this request.
18             request.Credentials = CredentialCache.DefaultCredentials;
19             HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
20 
21             Console.WriteLine ("Content length is {0}", response.ContentLength);
22             Console.WriteLine ("Content type is {0}", response.ContentType);
23 
24             // Get the stream associated with the response.
25             Stream receiveStream = response.GetResponseStream ();
26 
27             // Pipes the stream to a higher level stream reader with the required encoding format. 
28             StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
29 
30             Console.WriteLine ("Response stream received.");
31             Console.WriteLine (readStream.ReadToEnd ());
32             response.Close ();
33             readStream.Close ();
34         }
35     }
36 
37 /*
38 The output from this example will vary depending on the value passed into Main 
39 but will be similar to the following:
40 
41 Content length is 1542
42 Content type is text/html; charset=utf-8
43 Response stream received.
44 <html>
45 ...
46 </html>
47 
48 */


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM