CSharp - Post请求宝塔邮局发件api问题

2022年06月19日 · 笔记 · CSharp · 188次阅读

描述

简单描述一下问题:
使用C#发送POST请求给宝塔邮局发邮件的api时,出现错误代码500,
在ApiPost6、Python官方示例中,请求可以正确发送,返回200。

正常的POST代码

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;
}

标签:C#

最后编辑于:2022-06-19 20:30

评论

  1. 2022-06-20 13:53

    回复

Lover

搜一搜

云资源站点