首页 新闻 会员 周边 捐助

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

0
悬赏园豆:20 [已解决问题] 解决于 2022-06-27 17:27

先说明,对方提供的账号,对方随意开,不能一致是英文,所以报错了。
我这边改编码,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;
}

快乐的langYa的主页 快乐的langYa | 菜鸟二级 | 园豆:280
提问于:2022-06-27 13:13
< >
分享
最佳答案
0

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

收获园豆:20
jzblive | 菜鸟二级 |园豆:428 | 2022-06-27 14:00

转了之后就变了。对方API无法识别,我用PHP没有出现这问题。。

快乐的langYa | 园豆:280 (菜鸟二级) | 2022-06-27 15:31

@快乐的langYa: urlencode试一下呢

jzblive | 园豆:428 (菜鸟二级) | 2022-06-27 16:16
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册