【问题标题】:Getting text from web request从网络请求中获取文本
【发布时间】:2015-01-21 04:31:13
【问题描述】:

这是我的代码:

            Uri myUri = new Uri("my url");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create (myUri);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

            Console.WriteLine ("Content length is {0}", response.ContentLength);
            Console.WriteLine ("Content type is {0}", response.ContentType);

            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream ();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

            Console.WriteLine ("Response stream received.");
            Console.WriteLine (readStream.ReadToEnd ());
            response.Close ();
            readStream.Close ();

响应应该是这样的:

[
    {
        "book_name": "CYRILLIC LETTERS",
        "book_id": "Text",
    },
    {
        "book_name": "CYRILLIC LETTERS",
        "book_id": "Text",
    },
]

StreamReader.ReadToEnd() 正在返回我想要的所有内容,但它将西里尔字母替换为数字,例如:\u041c\u0410\u0422\u0422\u041e

我应该怎么做才能正确获取所有内容?

【问题讨论】:

    标签: c# json encoding cyrillic


    【解决方案1】:

    你用 Unicode 试过了吗?

    StreamReader readStream = new StreamReader (receiveStream, Encoding.Unicode);
    

    或者这个:

    System.Text.UnicodeEncoding encodingUNICODE = new System.Text.UnicodeEncoding();
    byte[] textBytesCyrillic = encodingUNICODE.GetBytes(readStream.ToString());
    
    Console.WriteLine ("Response stream received.");
    Console.WriteLine (encodingUNICODE.GetString(textBytesCyrillic));
    

    基于此thread,您已经获得了字符串形式的西里尔字母值。如果您可以显示西里尔字母的原始形式,请尝试答案的建议。

    【讨论】:

    • 如果我将其更改为编码为 Unicode,那么一切都是问号。
    • 您的第一个示例将所有内容显示为问号,第二个示例显示“System.IO.StreamReader”。你在你的电脑上试过了吗?
    • 我的错误首先,我在我的电脑上尝试过,但只使用了一个简单的西里尔字符串,并且可以工作
    • 我尝试了同样的事情。我将文本放入 txt 文件并使用带有 Encoding.UTF8 的 StreamWriter 读取文本。它工作正常。仅当文本来自网络请求时才发出。
    • 根据这个link,你得到的结果是你从网络请求中得到的西里尔字母的字符串表示,这意味着你已经有了你的西里尔字母。尝试将其传递给您的视图或我提供的链接中的建议。
    猜你喜欢
    • 2018-08-15
    • 2021-12-26
    • 2021-08-07
    • 2020-07-20
    • 2021-04-25
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多