C# HttpRequest 中文编码问题
工作中的项目要用到别家的网络短信平台,工作中遇到中文编码的问题,特总结以备忘。
GET方法:
public string DoWebRequest(string url)
{
HttpWebResponse webResponse = null;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
string responseStr = null;
webRequest.Timeout = 50000;
webRequest.ContentType = "text/html; charset=gb2312";
try
{
//尝试获得要请求的URL的返回消息
webResponse = (HttpWebResponse)webRequest.GetResponse();
}
catch (WebException e)
{
//发生网络错误时,获取错误响应信息
responseStr = "发生网络错误!请稍后再试";
}
catch (Exception e)
{
//发生异常时把错误信息当作错误信息返回
responseStr = "发生错误:" + e.Message;
}
finally
{
if (webResponse != null)
{
//获得网络响应流
using (StreamReader responseReader = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("GB2312")))
{
responseStr = responseReader.ReadToEnd();//获得返回流中的内容
}
webResponse.Close();//关闭web响应流
}
}
return responseStr;
}
注意:url中的中文,要先用HttpUtility.UrlEncode("内容",编码) 用服务器接收的编码,编码一下。
POST方法:
private string DoWebRequestByPost(string url, string param)
{
HttpWebResponse webResponse = null;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
//使用post方式提交
webRequest.Method = "POST";
string responseStr = null;
webRequest.Timeout = 50000;
//要post的字节数组
byte[] postBytes = encoding.GetBytes(param);
webRequest.ContentType = "application/x-www-form-urlencoded;";
webRequest.ContentLength = postBytes.Length;
using (Stream reqStream = webRequest.GetRequestStream())
{
reqStream.Write(postBytes, 0, postBytes.Length);
}
try
{
//尝试获得要请求的URL的返回消息
webResponse = (HttpWebResponse)webRequest.GetResponse();
}
catch (Exception)
{
//出错后直接抛出
throw;
}
finally
{
if (webResponse != null)
{
//获得网络响应流
using (StreamReader responseReader = new StreamReader(webResponse.GetResponseStream(), encoding))
{
responseStr = responseReader.ReadToEnd();//获得返回流中的内容
}
webResponse.Close();//关闭web响应流
}
}
return responseStr;
}
encoding为服务器接收的编码,例如:Encoding.GetEncoding("GBK")等
param post请求的参数 param1=123¶m2=中国¶m3=abc 这样的格式,中文部分不用使用编码,方法内转成byte[]时 会进行编码。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!