简单描述一下问题:
使用C#发送POST请求给宝塔邮局发邮件的api时,出现错误代码500,
在ApiPost6、Python官方示例中,请求可以正确发送,返回200。
public static string ApiPost(string url, Dictionary<string, string> parameters)
{
try
{
Encoding charset = Encoding.UTF8;
HttpWebRequest request = null;
//HTTPSQ请求
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
request = (HttpWebRequest)WebRequest.Create(url.Trim());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//如果需要POST数据
if (!(parameters == null || parameters.Count == 0))
{
var buffer = new StringBuilder();
foreach (var key in parameters.Keys)
{
string str = System.Web.HttpUtility.UrlEncode(parameters[key]);
buffer.AppendFormat(buffer.Length > 0 ? "&{0}={1}" : "{0}={1}", key, str);
}
byte[] data = charset.GetBytes(buffer.ToString());
request.ContentLength = data.Length;
request.GetRequestStream().Write(data, 0, data.Length);
}
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
}
Stream htmlStream = response.GetResponseStream();
StreamReader sr = new StreamReader(htmlStream, Encoding.UTF8);
var html = sr.ReadToEnd();
return html;
}
catch (Exception e)
{
Console.WriteLine($"api:{url} 异常:{e.Message}");
return null;
}
}
使用Fiddler
抓包工具,抓取正常200和错误500的,进行比较,发现
C#在POST请求是自动加上了request.Expect
这个表头的属性,我们只需要把它去掉就行,
去掉后有几率会发送请求失败,需要加入一个错误重试,就能增大请求成功几率。
此代码即可正常请求宝塔邮局发邮件的api
public static string ApiPost(string url, Dictionary<string, string> parameters)
{
//重试3次
int recount = 0;
while(recount < 3)
try
{
Encoding charset = Encoding.UTF8;
HttpWebRequest request = null;
//HTTPSQ请求
ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
request = (HttpWebRequest)WebRequest.Create(url.Trim());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = DefaultUserAgent;
request.Accept = "*/*";
request.Expect = null;
//如果需要POST数据
if (!(parameters == null || parameters.Count == 0))
{
var buffer = new StringBuilder();
foreach (var key in parameters.Keys)
{
string str = System.Web.HttpUtility.UrlEncode(parameters[key]);
buffer.AppendFormat(buffer.Length > 0 ? "&{0}={1}" : "{0}={1}", key, str);
}
byte[] data = charset.GetBytes(buffer.ToString());
request.ContentLength = data.Length;
request.GetRequestStream().Write(data, 0, data.Length);
}
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
recount++;
continue;
}
Stream htmlStream = response.GetResponseStream();
StreamReader sr = new StreamReader(htmlStream, Encoding.UTF8);
var html = sr.ReadToEnd();
return html;
}
catch (Exception e)
{
Console.WriteLine($"api:{url} 异常:{e.Message}");
recount++;
continue;
}
return null;
}