C#开发笔记之18-如何用C#模拟(传统方法)发送Post请求或Get请求?

C#开发笔记之18-如何用C#模拟(传统方法)发送Post请求或Get请求?

C#开发笔记概述

文章目录

概述

HTTP 协议是以 ASCII 码传输,建立在 TCP/IP 协议之上的应用层规范。HTTP 请求方法种类包含 OPTIONS、GET、HEAD、POST、PUT、DELETE、TRACE、CONNECT 等。

那么,如何使用C#模拟(传统方法)发送Post请求或Get请求呢?

解释

public static class PostHelper {

    private static readonly string DefaultUserAgent =
        "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " +
        "Chrome/63.0.3239.132 Safari/537.36";

    private static bool CheckValidationResult(object sender,
        X509Certificate certificate,
        X509Chain chain,
        SslPolicyErrors errors) {
        return true;
    }

    /// <summary>
    /// Url_encoding
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string UrlEncode(string str) {
        var sb = new StringBuilder();
        var byStr = Encoding.UTF8.GetBytes(str);

        for (var i = 0; i < byStr.Length; i++) {
            sb.Append(@"%" + Convert.ToString(byStr[i], 16));
        }

        return (sb.ToString().ToUpper());
    }

    /// <summary>
    /// 提供一个将数据POST到指定URL的方法
    /// </summary>
    /// <param name="url">要POST数据的地址</param>
    /// <param name="postDataStr">参数列表,param1=666%param2=888</param> 
    /// <returns>POST成功或失败</returns>
    public static string Post(string url,
                                string postDataStr = "") {
        ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        var encoding = Encoding.UTF8;
        var request = (HttpWebRequest)WebRequest.Create(url);

        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postDataStr.Length;

        byte[] payload;
        payload = encoding.GetBytes(postDataStr);
        request.ContentLength = payload.Length;

        var writer = request.GetRequestStream();
        writer.Write(payload, 0, payload.Length);
        writer.Close();

        var response = (HttpWebResponse)request.GetResponse();
        var reader = new StreamReader(response.GetResponseStream(), encoding);

        var retString = reader.ReadToEnd();
        return retString;
    }

    /// <summary>
    /// 发送Get请求
    /// </summary>
    /// <param name="url">地址</param>
    /// <param name="dic">请求参数定义</param>
    /// <returns></returns>
    public static string Get(string url, Dictionary<string, string> dic) {
        var result = string.Empty;

        var builder = new StringBuilder();
        builder.Append(url);

        if (dic.Count > 0) {
            builder.Append("?");
            var i = 0;

            foreach (var item in dic) {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
        }

        var req = (HttpWebRequest)WebRequest.Create(builder.ToString());

        req.Method = "GET";
        req.Host = "www.baidu.com";
        req.UserAgent = DefaultUserAgent;
        req.Accept = "*/*";
        req.KeepAlive = true;
        req.UserAgent = "PostmanRuntime/7.24.1";

        req.AllowAutoRedirect = true;

        //添加参数
        var resp = (HttpWebResponse)req.GetResponse();
        var stream = resp.GetResponseStream();

        try {
            //获取内容
            using (var reader = new StreamReader(stream)) {
                result = reader.ReadToEnd();
            }
        }
        finally {
            stream.Close();
        }

        return result;
    }

}

本文由 .Net中文网 原创发布,欢迎大家踊跃转载。

转载请注明本文地址:https://www.byteflying.com/archives/3445

发表评论

登录后才能评论