簡體   English   中英

在C#中獲取網頁內容和HTTP狀態代碼

[英]Get webpage page content and HTTP status code in C#

在C#Windows窗體應用程序中,我可以使用以下命令獲取網頁的內容:

string content = webClient.DownloadString(url);

我可以使用以下方式獲取HTTP標頭:

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

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

謝謝。

您可以在HttpWebResponse對象中讀取Stream中的數據:

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();
}

Web客戶端

我假設你使用WebClient因為它簡單的webrequest-to-string處理。 不幸的是, WebClient不公開HTTP響應代碼。 您可以假設響應是肯定的( 2xx ),除非您得到異常並閱讀它

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

或者,如果您對成功代碼真的感興趣,可以使用此處所述的反射。


HttpClient的

如果您使用的是.NET 4.5,也可以使用HttpClient ,它會公開響應代碼, 如下所述

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

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

HttpWebRequest的

或者,您可以使用HttpWebRequest獲取狀態和響應, 如下所述

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;    
}

我想,你還沒有意識到,在第二種情況下你也可以訪問內容(盡管需要花費更多的精力才能獲得一個字符串)。

查看Microsoft文檔: http//msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream (v=vs.110) .aspx ,它向您展示如何從Web獲取響應流響應,然后如何從該流中獲取字符串數據。

我可以使用以下命令獲取HTTP標頭:request.Method =“GET”;

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM