使用https post 调用接口(不带证书)

/// <summary>
        /// 使用https post 调用接口
        /// </summary>
        /// <param name="url">接口地址</param>
        /// <param name="pm_str">参数</param>
        /// <param name="pm_ContentType">application/x-www-form-urlencoded</param>
        /// <param name="myDictionary">hender没有就给NUll</param>
        /// <returns></returns>
        public static string PostUrl(string url, string pm_str, string pm_ContentType, Dictionary<string, string> myDictionary)
        {
            //string headstr = null;
            StreamReader reader = null;
            Stream requestStream = null;
            HttpWebResponse Response = null;
            try
            {
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(url);
                myReq.Method = "POST";
                if (pm_ContentType != null)
                {
                    myReq.ContentType = pm_ContentType;
                }
                if (myDictionary != null)
                {
                    foreach (KeyValuePair<string, string> kvp in myDictionary)
                    {
                        myReq.Headers.Add(kvp.Key, kvp.Value);
                    }

                    // myReq.Headers.Add("Authorization", "Basic " + headstr);
                }
                byte[] bz = System.Text.Encoding.UTF8.GetBytes(pm_str);
                myReq.ContentLength = bz.Length;
                requestStream = myReq.GetRequestStream();
                requestStream.Write(bz, 0, bz.Length);
                requestStream.Close();
                requestStream = null;
                //myReq.Timeout = 30000;

                Response = (HttpWebResponse)myReq.GetResponse();
                reader = new StreamReader(Response.GetResponseStream(), Encoding.UTF8);
                string retstr = reader.ReadToEnd().Trim();
                return retstr;
            }
            catch (Exception ex)
            {
                return "{\"code\":\"E\",\"msg\":\"ERR" + ex.Message.ToString() + "\"}";
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                    reader = null;
                }
                if (requestStream != null)
                {

                }

            }
        }
    }

 

posted @ 2021-12-31 10:55  旧夏潜入梦  阅读(352)  评论(0编辑  收藏  举报