ReadAsStringAsync返回报错
public class RequestHelper { private static readonly HttpClient _httpClient = new HttpClient(); public static async Task<string> GetRequest(string url, string token = "") { var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (!string.IsNullOrEmpty(token)) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); } var response = await _httpClient.SendAsync(request); response.EnsureSuccessStatusCode(); //返回byte,转换成utf8,防止报错 var bytes = await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); var str= Encoding.UTF8.GetString(bytes); return str; //return await response.Content.ReadAsStringAsync().ConfigureAwait(false);//直接返回json,有时候会报utf8不支持的错误 } }
使用ReadAsStringAsync调用api返回json时,有时会报如下错误
utf8' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method. (Parameter 'name')
浙公网安备 33010602011771号