在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的内容。