我在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方式,请问如何怎么修改?我红色部分代码