问下各位,我 c#调用httppost调用webapi,也用postman做了测试是可以的,也写了代码了,为何我程序端运行,还是出错?

草履虫程序员 CSDN会员 草履虫程序员 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我在c# winform程序里调用第三方提供的api,也通过postman测试是正常的,现在通过c#写了一段函数,访问,一直有问题。
1.postman的测试ui header部分

2.postman的测试ui body部分


3.我的访问的函数代码如下:
public static string PostFunc(string apiUrl, string token, string param)
{
string strJson = string.Empty;
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
ASCIIEncoding encoding = new ASCIIEncoding();
request = WebRequest.Create(apiUrl) as HttpWebRequest;
request.AllowWriteStreamBuffering = true;//
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

byte[] b = Encoding.UTF8.GetBytes(param);
//Header中添加token验证(服务器要求)
request.Headers.Add("eg-token", token);//添加token到header
request.Headers.Add("Content-Type", "application/json");
//request.ContentType = "application/json";//已有token使用json类型
request.ContentLength = b.Length;
request.Method = "POST";
if (b.Length > 0)
{
using (Stream stream = request.GetRequestStream())
{
stream.Write(b, 0, b.Length);
stream.Close();
}
}
//获取服务器返回
using (response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
strJson = reader.ReadToEnd();
reader.Close();
}
}
return strJson;
}
catch (Exception exception)
{
return exception.Message;
}
finally
{
if (response != null)
response.Close();
}
}
对照postman方式,请问如何怎么修改?我红色部分代码
...全文

相关推荐

评论 11
收藏 已收藏
分享
返回顶部
草履虫程序员 CSDN会员
Web Services 12,164 成员 16,322 内容