HttpWebRequest类的Headers.Add中的值是有特殊符号时报错

先说明,对方提供的账号,对方随意开,不能一致是英文,所以报错了。
我这边改编码,API对面是乱码。
值是:国际一210621,含有

public static string Post(string url, Dictionary<string, object> param, Dictionary<string, string> headers = null)
{
// 支持https
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// 建立请求
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.AllowAutoRedirect = true;
request.MaximumResponseHeadersLength = 1024;
request.Method = "POST";
request.AllowAutoRedirect = true;
request.MaximumResponseHeadersLength = 1024;
request.ContentType = "Content-type:application/json;charset=UTF-8";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.53 Safari/537.36 Edg/103.0.1264.37";
if (headers != null)
{
foreach (var item in headers)
{

// 这里报错
request.Headers.Add(item.Key, item.Value);
}
}
string jsonstring = string.Empty;//得到参数的json字符串
if (param.Count != 0) //将参数添加到json对象中
{
jsonstring = JsonConvert.SerializeObject(param);
}

byte[] jsonbyte = Encoding.UTF8.GetBytes(jsonstring);
Stream postStream = request.GetRequestStream();
postStream.Write(jsonbyte, 0, jsonbyte.Length);
postStream.Close();
//发送请求并获取相应回应数据
HttpWebResponse res;
try
{
res = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
res = (HttpWebResponse)ex.Response;
}
StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
string content = sr.ReadToEnd(); //得到响应字符串
sr.Close();
return content;
}

回答

header 传参只允许ASCII码,转一下BASE64

THE END
分享
二维码
< <上一篇
下一篇>>