C# https post formdata调用接口

2022/2/23 12:21:20

本文主要是介绍C# https post formdata调用接口,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

using Newtonsoft.Json.Linq;

using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json;
using System.IO;
using System.Net;
  private static readonly string DefaultUserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36";
 private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
``

 public static string Base64Encode(Encoding encodeType, string source)
        {
            string encode = string.Empty;
            byte[] bytes = encodeType.GetBytes(source);
            try
            {
                encode = Convert.ToBase64String(bytes);
            }
            catch
            {
                encode = source;
            }
            return encode;
        }`
 public static string GetFormdata(Dictionary<string, string> dic, string ticks)
        {
            string Info = "";
            string Head = string.Format("----------------------------{0}", ticks);
            string Foot = string.Format("----------------------------{0}--", ticks);
            foreach (var item in dic)
            {
                Info += string.Format("{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", Head, item.Key, item.Value);
            }
            Info += Foot;
            return Info;
        }

  #region formdata格式获取AccessToken
        public static string PostAccessTokenByHttps()
        {
            try
            {
                string jsonlist = "";
                string access_token = "";
                string Ticks = DateTime.Now.Ticks.ToString();
                //从配置文件获取固定数据
                string comid = System.Configuration.ConfigurationManager.AppSettings["HLYCompanyID"];
                string comkey = System.Configuration.ConfigurationManager.AppSettings["HLYCompanyKey"];
                string url = System.Configuration.ConfigurationManager.AppSettings["HLYJKTokenURL"];
                HttpWebRequest request = null;
                CookieContainer cookie = new CookieContainer();
                //HTTPSQ请求
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.CookieContainer = cookie;
                request.ProtocolVersion = HttpVersion.Version11;
                request.Method = "POST";
                //request.ContentType = "application/x-www-form-urlencoded";
                //request.ContentType = "application/json;charset=UTF-8";
                request.ContentType = string.Format("multipart/form-data; boundary=--------------------------{0}", Ticks);
                request.UserAgent = DefaultUserAgent;
                request.KeepAlive = true;
                string source = comid + ':' + comkey;
                **//注意Basic后面有空格**
                string Authorization = "Basic " + Base64Encode(Encoding.UTF8, source);
                request.Headers["Authorization"] = Authorization;
                //  request.Timeout = 300000;
                //request.Headers["Cookie"] = "username=aaaaaa; Language=zh_CN";
                //如果需要POST数据   
                Dictionary<string, string> dic = new Dictionary<string, string>();
                dic.Add("grant_type", "client_credentials");
                dic.Add("scope", "write");
                //StringBuilder builder = new StringBuilder();
                //int i = 0;
                //foreach (var item in dic)
                //{
                //    if (i > 0)
                //        builder.Append("&");
                //    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                //    i++;
                //}

                string Paramter = GetFormdata(dic, Ticks);
                byte[] byteData = Encoding.UTF8.GetBytes(Paramter);
                int length = byteData.Length;
                request.ContentLength = length;
                //证书,要求.net framework 4.5.1及以上
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(byteData, 0, byteData.Length);
                }
                var response = (HttpWebResponse)request.GetResponse();
                using (StreamReader st = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    jsonlist = st.ReadToEnd().ToString();
                    // return st.ReadToEnd().ToString();
                    JObject jo = (JObject)JsonConvert.DeserializeObject(jsonlist);
                    access_token = jo["access_token"].ToString();
                }
                return access_token;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }
        #endregion


这篇关于C# https post formdata调用接口的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程