菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
263
0

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

原创
05/13 14:22
阅读数 64532

 

当前框架版本.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/200
263 点赞
0 评论
收藏
为你推荐 换一批