2013-11-26 61 views
6

在C#Windows窗體應用程序,我可以用得到一個網頁的內容:獲取網頁的頁面內容和HTTP狀態代碼在C#

string content = webClient.DownloadString(url); 

我可以用得到的HTTP標頭:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
request.Method = "GET"; 
string response = ((HttpWebResponse)request.GetResponse()).StatusCode.ToString(); 

有沒有辦法在服務器上一次訪問內容和HTTP狀態碼(如果失敗),而不是兩次?

謝謝。

+0

呵呵?你使用GET,所以你得到GET。問題在哪裏? –

+1

'request.GetResponse()'讓你們都得到了。你是那個只從中獲取'StatusCode'的人。 – Tobberoth

回答

5

您可以從流讀取的數據HttpWebResponse對象中:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
request.Method = "GET"; 
using (var response = request.GetResponse()) 
using (var stream = response.GetResponseStream()) 
using (var reader = new StreamReader(stream)) 
{ 
    HttpStatusCode statusCode = ((HttpWebResponse)response).StatusCode; 
    string contents = reader.ReadToEnd(); 
} 

這樣,你就必須手動檢測的編碼,或者使用庫來檢測編碼。您也可以從HttpWebResponse對象中讀取編碼作爲字符串,當存在時,它位於ContentType屬性內。如果頁面是Html,那麼您將不得不解析它,以便在文檔頂部或頭部內部進行可能的編碼更改。

讀取處理來自ContentType標頭編碼

var request = (HttpWebRequest)WebRequest.Create(url); 
request.Method = "GET"; 
string content; 
HttpStatusCode statusCode; 
using (var response = request.GetResponse()) 
using (var stream = response.GetResponseStream()) 
{ 
    var contentType = response.ContentType; 
    Encoding encoding = null; 
    if (contentType != null) 
    { 
     var match = Regex.Match(contentType, @"(?<=charset\=).*"); 
     if (match.Success) 
      encoding = Encoding.GetEncoding(match.ToString()); 
    } 

    encoding = encoding ?? Encoding.UTF8; 

    statusCode = ((HttpWebResponse)response).StatusCode; 
    using (var reader = new StreamReader(stream, encoding)) 
     content = reader.ReadToEnd(); 
} 
3

WebClient的

我假設你使用WebClient,因爲它很容易的WebRequest到字符串處理。不幸的是,WebClient不公開HTTP響應代碼。您可以假設反應是積極的(2xx),除非你得到一個exception and read it

try 
{ 
    string content = webClient.DownloadString(url); 
} 
catch (WebException e) 
{ 
    HttpWebResponse response = (System.Net.HttpWebResponse)we.Response;  
    var statusCode = response.StatusCode; 
} 

或者,如果你在成功的代碼,你可以使用反射作爲解釋here真正感興趣。


HttpClient的

您也可以使用HttpClient如果你在.NET 4。5,這無疑揭穿了響應代碼,as explained here

using (HttpClient client = new HttpClient()) 
{ 
    HttpResponseMessage response = await client.GetAsync(url); 

    string content = await response.Content.ReadAsStringAsync(); 
    var statusCode = response.StatusCode;  
} 

HttpWebRequest的

或者,你可以使用HttpWebRequest要獲得狀態和響應as explained here

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
request.Method = "GET"; 
var response = (HttpWebResponse)request.GetResponse(); 

using (Stream stream = response.GetResponseStream()) 
{ 
    StreamReader reader = new StreamReader(stream); 

    string content = reader.ReadToEnd(); 
    var statusCode = response.StatusCode;  
} 
0

我可以得到HTTP頭唱歌: request.Method =「GET」;

方法GET返回HEAD和BODY部分作爲響應。 HTTP也支持方法HEAD - 僅返回HEAD部分。

您可以使用GetResponseStream method從HttpWebResponse獲取BODY。