1

这是向远程网站发出请求的函数代码:

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 元标记。

我可以在我的代码中做些什么来使请求返回我需要的编码页面?

4

2 回答 2

1

检查response.ContentType。它应该包含一个charset=参数。您可以使用它来创建Encoding在创建StreamReader.

于 2012-04-20T03:35:35.760 回答
1

吉姆米歇尔的回答帮助了我。

如果你想知道如何设置 ContentType 和 CharSet,可以这样做:

var request = new HttpRequestMessage(HttpMethod.Post, "http://yourwebsite.com:80/Api/")
{
    Content = new StringContent(messageBodyAsString)
};
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json")
{
    CharSet = "utf-8"
};

然后请求将发送Content-Typeapplication/json; charset=utf-8

于 2017-08-10T08:56:38.500 回答