C# HttpWebRequest\HttpWebResponse\WebClient发送请求解析json数据 gzip压缩

C# HttpWebRequest\HttpWebResponse\WebClient发送请求解析json数据 gzip压缩在ASP.NETCore中使用IHttpClientFactory发出HTTP请求**======================================================================================================================================///<su…

在 ASP.NET Core 中使用 IHttpClientFactory 发出 HTTP 请求
在 ASP.NET Core 中使用 IHttpClientFactory 发出 HTTP 请求 6.0

HttpWebRequest【.NET早期版本,同步方式】
WebClient【HttpWebRequest的封装简化版,同步方式】
HttpClient    【.NET4.5以后,异步方式】
HttpClientFactory【.NET Core2.1】

获取当前时间、获取 WebHeaderCollection 参数

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

//方式一:获取当前时间
var lastModified = response.LastModified;
WebHeaderCollection headerCollection = response.Headers;
foreach (var h in headerCollection.AllKeys)
{
    if (h == "Date")
    {
        //方式二:获取当前时间
        var datetime = headerCollection[h];
        DateTime time = GMT2Local(headerCollection[h]);
    }
}

/// <summary>
/// GMT时间转成本地时间
/// Fri, 18 Mar 2022 13:55:32 GMT
/// </summary>
/// <param name="gmt">字符串形式的GMT时间</param>
/// <returns></returns>
public DateTime GMT2Local(string gmt)
{
    DateTime dt = DateTime.MinValue;
    try
    {
        string pattern = "";
        if (gmt.IndexOf("+0") != -1)
        {
            gmt = gmt.Replace("GMT", "");
            pattern = "ddd, dd MMM yyyy HH':'mm':'ss zzz";
        }
        if (gmt.ToUpper().IndexOf("GMT") != -1)
        {
            pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";
        }
        if (pattern != "")
        {
            dt = DateTime.ParseExact(gmt, pattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal);
            dt = dt.ToLocalTime();
        }
        else
        {
            dt = Convert.ToDateTime(gmt);
        }
    }
    catch
    {
    }
    return dt;
}

*

/// <summary>
/// 日期:2016-2-4
/// 备注:bug已修改,可以使用
/// </summary>
public static void Method1()
{
    try
    {
        string domain = "http://192.168.1.6:8098/";
        string url = domain + "/Signin/LoginApi";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        //request.ContentType = "application/json";
        request.ReadWriteTimeout = 30 * 1000;

        // 忽略证书
        request.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => {
            return true;
        };

        ///添加参数
        Dictionary<String, String> dicList = new Dictionary<String, String>();
        dicList.Add("UserName", "test@qq.com");
        dicList.Add("Password", "000000");
        String postStr = buildQueryStr(dicList);
        byte[] data = Encoding.UTF8.GetBytes(postStr);

        request.ContentLength = data.Length;

        Stream myRequestStream = request.GetRequestStream();
        myRequestStream.Write(data, 0, data.Length);
        myRequestStream.Close();

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        //当前时间
        var lastModified = response.LastModified;
        WebHeaderCollection headerCollection = response.Headers;
        foreach (var h in headerCollection.AllKeys)
        {
            if (h == "Date")
            {
                var datetime = headerCollection[h];
                DateTime time = GMT2Local(headerCollection[h]);
            }
        }

        StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
        var retString = myStreamReader.ReadToEnd();
        myStreamReader.Close();
    }
    catch (Exception ex)
    {
        log.Info("Entered ItemHierarchyController - Initialize");
        log.Error(ex.Message);
    }
}

/// <summary>
/// GMT时间转成本地时间
/// Fri, 18 Mar 2022 13:55:32 GMT
/// </summary>
/// <param name="gmt">字符串形式的GMT时间</param>
/// <returns></returns>
public DateTime GMT2Local(string gmt)
{
    DateTime dt = DateTime.MinValue;
    try
    {
        string pattern = "";
        if (gmt.IndexOf("+0") != -1)
        {
            gmt = gmt.Replace("GMT", "");
            pattern = "ddd, dd MMM yyyy HH':'mm':'ss zzz";
        }
        if (gmt.ToUpper().IndexOf("GMT") != -1)
        {
            pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";
        }
        if (pattern != "")
        {
            dt = DateTime.ParseExact(gmt, pattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal);
            dt = dt.ToLocalTime();
        }
        else
        {
            dt = Convert.ToDateTime(gmt);
        }
    }
    catch
    {
    }
    return dt;
}

升级版本,提取到帮助类,封装对象,gzip压缩

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace CMS.Common
{
    public class MyHttpClient
    {
        public string methodUrl = string.Empty;
        public string postStr = null;

        public MyHttpClient(String methodUrl)
        {
            this.methodUrl = methodUrl;
        }

        public MyHttpClient(String methodUrl, String postStr)
        {
            ///this.methodUrl = ConfigurationManager.AppSettings["ApiFrontEnd"];///http://192.168.1.6:8098/Signin/LoginApi
            ///this.postStr = postStr;

            this.methodUrl = methodUrl;
            this.postStr = postStr;
        }

        /// <summary>
        /// GET Method
        /// </summary>
        /// <returns></returns>
        public String ExecuteGet()
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(this.methodUrl);
            myRequest.Method = "GET";
            myRequest.Headers.Add("Accept-Encoding", "gzip, deflate, br");

            // 忽略证书
            myRequest.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => {
                return true;
            };

            HttpWebResponse myResponse = null;
            try
            {
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                StreamReader reader = new StreamReader(new GZipStream(myResponse.GetResponseStream(), CompressionMode.Decompress), Encoding.GetEncoding("utf-8"));
                string content = reader.ReadToEnd();
                return content;
            }
            //异常请求
            catch (WebException e)
            {
                myResponse = (HttpWebResponse)e.Response;
                using (Stream errData = myResponse.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(errData))
                    {
                        string text = reader.ReadToEnd();

                        return text;
                    }
                }
            }
        }

        /// <summary>
        /// POST Method
        /// </summary>
        /// <returns></returns>
        public string ExecutePost()
        {
            string content = string.Empty;

            Random rd = new Random();
            int rd_i = rd.Next();
            String nonce = Convert.ToString(rd_i);
            String timestamp = Convert.ToString(ConvertDateTimeInt(DateTime.Now));
            String signature = GetHash(this.appSecret + nonce + timestamp);

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.methodUrl);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                //request.ContentType = "application/json";
                request.Headers.Add("Nonce", nonce);
                request.Headers.Add("Timestamp", Convert.ToString(StringProc.ConvertDateTimeInt(DateTime.Now)));
                request.Headers.Add("Signature", signature);
                request.ReadWriteTimeout = 30 * 1000;

                // 忽略证书
                request.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => {
                    return true;
                };

                byte[] data = Encoding.UTF8.GetBytes(postStr);
                request.ContentLength = data.Length;

                Stream myRequestStream = request.GetRequestStream();

                myRequestStream.Write(data, 0, data.Length);
                myRequestStream.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                content = myStreamReader.ReadToEnd();
                myStreamReader.Close();
            }
            catch (Exception ex)
            {
            }
            return content;
        }

        /// <summary>
        /// POST Method 调用示例
        /// Dictionary<string, string> parm = new Dictionary<string, string>();
        /// parm.Add("user_name", "admin");
        /// parm.Add("password", "123456");
        /// var result = ExecutePost("http://******:9000/api/v1/passport/login", JsonConvert.SerializeObject(parm));
        /// </summary>
        /// <returns></returns>
        public string ExecutePost(string url, string data)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(data);
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            myRequest.Method = "POST";
            myRequest.ContentType = "application/json";
            myRequest.ContentLength = buffer.Length;

            // 忽略证书
            myRequest.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => {
                return true;
            };

            Stream newStream = myRequest.GetRequestStream();
            newStream.Write(buffer, 0, buffer.Length);
            newStream.Close();
            HttpWebResponse myResponse = null;
            try
            {
                myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string content = reader.ReadToEnd();
                return content;
            }
            //异常请求
            catch (WebException e)
            {
                myResponse = (HttpWebResponse)e.Response;
                using (Stream errData = myResponse.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(errData))
                    {
                        string text = reader.ReadToEnd();
                        LogUtils.GetInstance().Info($"Ln 152 {text}");
                        return text;
                    }
                }
            }
        }
    }

    public class StringProc
    {
        public static String buildQueryStr(Dictionary<String, String> dicList)
        {
            String postStr = "";

            foreach (var item in dicList)
            {
                postStr += item.Key + "=" + HttpUtility.UrlEncode(item.Value, Encoding.UTF8) + "&";
            }
            postStr = postStr.Substring(0, postStr.LastIndexOf('&'));
            return postStr;
        }

        public static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }
    }
}

前端调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CMS.Common;
using Newtonsoft.Json;

namespace Medicine.Web.Controllers
{
    public class DefaultController : Controller
    {
        public ActionResult Index()
        {
            #region DoGet

            string getResultJson = this.DoGet(url);
            HttpClientResult customerResult = (HttpClientResult)JsonConvert.DeserializeObject(getResultJson, typeof(HttpClientResult));

            #endregion

            #region DoPost

            string name = Request.Form["UserName"];
            string password = Request.Form["Password"];

            Dictionary<String, String> dicList = new Dictionary<String, String>();
            dicList.Add("UserName", name);
            dicList.Add("Password", password);
            string postStr = StringProc.buildQueryStr(dicList);

            string postResultJson = this.DoPost(url, postStr);
            HttpClientResult userResult = (HttpClientResult)JsonConvert.DeserializeObject(postResultJson, typeof(HttpClientResult));

            #endregion

            return View();
        }

        /// <summary>
        /// GET Method
        /// </summary>
        /// <param name="portraitUri">url地址</param>
        /// <returns></returns>
        private String DoGet(string portraitUri)
        {
            MyHttpClient client = new MyHttpClient(portraitUri);
            return client.ExecuteGet();
        }

        /// <summary>
        /// POST Method
        /// </summary>
        /// <param name="portraitUri">url地址</param>
        /// <param name="postStr">请求参数</param>
        /// <returns></returns>
        private String DoPost(string portraitUri, string postStr)
        {
            MyHttpClient client = new MyHttpClient(portraitUri, postStr);
            return client.ExecutePost();
        }

        public class HttpClientResult
        {
            public string UserName { get; set; }

            public bool Success { get; set; }
        }
    }
}

HttpClient

var responseString = string.Empty;
using (var client = new HttpClient())
{
    var values = new Dictionary<string, string>
    {
        { "apikey", apiKey },
        { "mobile", phoneNumber },
        { "text", smsMessage }
    };
    
    var content = new FormUrlEncodedContent(values);
    var response = await client.PostAsync(url, content);
    responseString = await response.Content.ReadAsStringAsync();
}

.net framework 3.5 版本,遇见“基础连接已关闭”的问题,尝试如下方法:

ServicePointManager.SecurityProtocol = (SecurityProtocolType)768;

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

微软官方文档说明:SecurityProtocolType 枚举 (System.Net) | Microsoft Docs

C# HttpWebRequest\HttpWebResponse\WebClient发送请求解析json数据 gzip压缩

忽略证书
myRequest.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => {

    return true;
}

今天的文章C# HttpWebRequest\HttpWebResponse\WebClient发送请求解析json数据 gzip压缩分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/26582.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注