Getting an UTF-8 response with httpclient in Windows Store apps

后端 未结 7 2382
清酒与你
清酒与你 2020-12-10 12:44

I\'m building a Windows Store app, but I\'m stuck at getting a UTF-8 response from an API.

This is the code:

using (HttpClient client = new HttpClien         


        
7条回答
  •  猫巷女王i
    2020-12-10 13:29

    I like El Marchewko's approach of using an extension, but the code did not work for me. This did:

    using System.IO;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace WannaSport.Data.Integration
    {
        public static class HttpContentExtension
        {
            public static async Task ReadAsStringUTF8Async(this HttpContent content)
            {
                return await content.ReadAsStringAsync(Encoding.UTF8);
            }
    
            public static async Task ReadAsStringAsync(this HttpContent content, Encoding encoding)
            {
                using (var reader = new StreamReader((await content.ReadAsStreamAsync()), encoding))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
    

提交回复
热议问题