您可以從流讀取的數據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();
}
呵呵?你使用GET,所以你得到GET。問題在哪裏? –
'request.GetResponse()'讓你們都得到了。你是那個只從中獲取'StatusCode'的人。 – Tobberoth