这是向远程网站发出请求的函数代码:
private static string translatePage(string text, string langPair, Encoding encoding) {
string urlBabelfish = "http://babelfish.yahoo.com/translate_txt";
string urlReverso = "http://www.reverso.net/text_translation.aspx?lang=RU#";
string url = "";
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(urlBabelfish);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = string.Format("lp={0}&trtext={1}", langPair, text);
byte[] byteArray = encoding.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(
request.ContentType);
ct.CharSet = encoding.ToString();
request.ContentType = ct.ToString();
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
string resPage = "";
using (dataStream)
{
using (StreamReader sr = new StreamReader(dataStream, encoding))
resPage = sr.ReadToEnd();
}
response.Close();
return resPage;
}
使用输入参数调用此函数langPair="en_ru"
会返回一个编码错误且不允许西里尔符号的页面。ContentType 元标记如下所示:
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
所有西里尔符号都变为'\0'
.
如果我在浏览器中使用相同的参数手动执行请求,它会返回UTF-8
带有标签的精细编码页面
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">.
我希望我的代码也这样做。我作为编码参数传递UTF-8
,但它不影响 ContentType 元标记。
我可以在我的代码中做些什么来使请求返回我需要的编码页面?