菜单 学习猿地 - LMONKEY

ArgumentException: 'gb2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.

shrimp profile image shrimp ・1 min read

 

当前框架版本.Net 5.0

问题:.net core中使用GB2312编码的问题

ArgumentException: 'gb2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.

 

The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set.”
ArgumentException:
'gb2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method. Arg_ParamName_Name

 

 

解决方案:

在调用请求时候,注册字符集:

//注册字符集
                System.Text.EncodingProvider provider = System.Text.CodePagesEncodingProvider.Instance;
                Encoding.RegisterProvider(provider);

 

 

使用案例:

HttpClient client = new HttpClient();
using (MemoryStream ms = new MemoryStream())
{

    byte[] bytes = Encoding.UTF8.GetBytes(paramJson);
    ms.Write(bytes, 0, bytes.Length);

    HttpContent hc = new StreamContent(ms);
    hc.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    hc.Headers.ContentEncoding.Add("utf-8");

    //注册字符集
    System.Text.EncodingProvider provider = System.Text.CodePagesEncodingProvider.Instance;
    Encoding.RegisterProvider(provider);

    HttpResponseMessage resp = await client.PostAsync(url, hc);

    string result = await resp.Content.ReadAsStringAsync();
    //判断结果处理
}

 

更多:

.Net Core 发送https请求/.net core 调用数字证书 使用X509Certificate2

.Net Standard HttpClient封装Htt请求常用操作整理

.Net Standard 类库的创建和使用

评论 (0)