How to change the encoding of the HttpClient response

前端 未结 3 1519
我在风中等你
我在风中等你 2020-12-17 17:38

I\'m trying to learn about Async programming using VS2012 and its Async Await keyword. That is why i wrote this piece of code:



        
相关标签:
3条回答
  • 2020-12-17 17:54

    In case you want a more generic method, following works in my UWP case in case someone has one with Unicode, would be great add the if:

    var response = await httpclient.GetAsync(urisource);
    
    if (checkencoding)
    {
        var contenttype = response.Content.Headers.First(h => h.Key.Equals("Content-Type"));
        var rawencoding = contenttype.Value.First();
    
        if (rawencoding.Contains("utf8") || rawencoding.Contains("UTF-8"))
        {
            var bytes = await response.Content.ReadAsByteArrayAsync();
            return Encoding.UTF8.GetString(bytes);
        }
    }
    
    0 讨论(0)
  • 2020-12-17 18:18

    WinRT 8.1 C#

    using Windows.Storage.Streams;
    using System.Text;
    using Windows.Web.Http;
    
    // in some async function
    
    Uri uri = new Uri("http://something" + query);
    HttpClient httpClient = new HttpClient();
    
    IBuffer buffer = await httpClient.GetBufferAsync(uri);
    string response = Encoding.UTF8.GetString(buffer.ToArray(), 0, (int)(buffer.Length- 1));
    
    // parse here
    
    httpClient.Dispose();
    
    0 讨论(0)
  • 2020-12-17 18:19

    You may have to check the encoding options and get the correct one. Otherwise, this code should get you going with the response.

    private async Task<string> GetResultsAsync(string uri)
    {
        var client = new HttpClient();
        var response = await client.GetByteArrayAsync(uri);
        var responseString = Encoding.Unicode.GetString(response, 0, response.Length - 1);
        return responseString;
    }
    
    0 讨论(0)
提交回复
热议问题