在C#中處理Response的編碼問題可以通過以下幾種方式:
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8; // 設置編碼格式為UTF-8
string response = client.DownloadString("http://example.com");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream, Encoding.UTF8); // 設置編碼格式為UTF-8
string responseData = reader.ReadToEnd();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string contentType = response.ContentType;
Encoding encoding = Encoding.GetEncoding("utf-8");
if (!string.IsNullOrEmpty(contentType))
{
Match match = Regex.Match(contentType, "charset=([A-Za-z0-9-]+)");
if (match.Success)
{
encoding = Encoding.GetEncoding(match.Groups[1].Value);
}
}
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
string responseData = reader.ReadToEnd();
通過以上方法,可以有效處理Response的編碼問題,確保正確解析Response的內容。