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

后端 未结 7 2311
清酒与你
清酒与你 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条回答
  • 2020-12-10 13:31

    My approach using an Extension:

        using System;
        using System.Collections.Generic;
        using System.IO;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using Windows.Web.Http;
    
        namespace yourfancyNamespace
        {
            public static class IHttpContentExtension
            {
                public static async Task<string> ReadAsStringUTF8Async(this IHttpContent content)
                {
                    return await content.ReadAsStringAsync(Encoding.UTF8);
                }
                public static async Task<string> ReadAsStringAsync(this IHttpContent content, Encoding encoding)
                {
                    using (TextReader reader = new StreamReader((await content.ReadAsInputStreamAsync()).AsStreamForRead(), encoding))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题