/// <summary>
        /// POST方式提交 application/json
        /// </summary>
        /// <param name="postUrl">请求地址</param>
        /// <param name="paramData">入参</param>
        /// <param name="dataEncode">编码方式</param>
        /// <returns></returns>
        public string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
        {
            string ret = string.Empty;
            try
            {
               
                byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //一定要有这一句
                ServicePointManager.ServerCertificateValidationCallback = delegate(
                Object obj, X509Certificate certificate, X509Chain chain,
                SslPolicyErrors errors)
                {
                    return (true);
                };

                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));

                webReq.Method = "POST";
                webReq.ContentType = "application/json";
                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
               
            }
            catch (Exception ex)
            {
                MessageBoxs.ShowError(ex.Message);
            }
            return ret;
        }

        /// <summary>
        /// POST方式提交 application/json
        /// </summary>
        /// <param name="postUrl">请求地址</param>
        /// <param name="paramData">入参</param>
        /// <param name="dataEncode">编码方式</param>
        /// <returns></returns>
        public string PostWebRequest(string postUrl, string paramData)
        {
            string ret = string.Empty;
            try
            {
               
                byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //一定要有这一句
                ServicePointManager.ServerCertificateValidationCallback = delegate(
                Object obj, X509Certificate certificate, X509Chain chain,
                SslPolicyErrors errors)
                {
                    return (true);
                };
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/json";
                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();

               
            }
            catch (Exception ex)
            {
                MessageBoxs.ShowError(ex.Message);
            }

            return ret;
        }

        /// <summary>
        /// POST方式提交 multipart/form-data
        /// </summary>
        /// <param name="postUrl">请求的拼接地址及入参(示例:http://ip:端口?a=1&b=2)</param>
        /// <returns></returns>
        public string PostRequest(string strInterFaceName, string postUrl)
        {     
            string ret = string.Empty;
            try
            {
                  byte[] byteArray = Encoding.UTF8.GetBytes(postUrl); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "multipart/form-data";

                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
             
            }
            catch (Exception ex)
            {
                MessageBoxs.ShowError(ex.Message);
            }
            return ret;
        }


        /// <summary>
        /// Get提交方式
        /// </summary>
        /// <param name="getUrl">请求地址</param>
        /// <returns></returns>
        public string GetWebRequest(string getUrl)
        {
            string responseStr = string.Empty;
            try
            {
               
                WebRequest myWebRequest = WebRequest.Create(getUrl);
                WebResponse myWebResponse = myWebRequest.GetResponse();
                Stream ReceiveStream = myWebResponse.GetResponseStream();

                if (ReceiveStream != null)
                {
                    StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
                myWebResponse.Close();

             
            }
            catch (Exception ex)
            {
               
            }

            return responseStr;
        }

        /// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <returns></returns>
        public  string Post(string url)
        {
            string result = "";
         
            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //一定要有这一句
            ServicePointManager.ServerCertificateValidationCallback = delegate(
            Object obj, X509Certificate certificate, X509Chain chain,
            SslPolicyErrors errors)
            {
                return (true);
            };


            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        /// <summary>
        /// 发送JSON请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="json">请求JSON</param>
        /// <param name="timeout">超时时间(秒)</param>
        /// <returns>响应对象</returns>
        public T PostJson<T>(string url, object json, int timeout = 10)
        {
            try
            {
                var jsonString = JsonConvert.SerializeObject(json);
                var jsonBytes = Encoding.UTF8.GetBytes(jsonString);
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //一定要有这一句
                ServicePointManager.ServerCertificateValidationCallback = delegate(
                Object obj, X509Certificate certificate, X509Chain chain,
                SslPolicyErrors errors)
                {
                    return (true);
                };

                HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
              
                request.Method = "POST";
                request.ContentType = "application/json;charset=UTF-8";
                request.ContentLength = jsonBytes.Length;
                request.Timeout = timeout * 1000;
                ServicePointManager.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return true; };
                using (var writer = request.GetRequestStream())
                {
                    writer.Write(jsonBytes, 0, jsonBytes.Length);

                    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("请求失败:{0}", ex.Message));
            }
        }

        /// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <returns></returns>
        public T DicPost<T>(string url, Dictionary<string, string> dic)
        {
            //string result = "";
            try
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //一定要有这一句
                ServicePointManager.ServerCertificateValidationCallback = delegate(
                Object obj, X509Certificate certificate, X509Chain chain,
                SslPolicyErrors errors)
                {
                    return (true);
                };

                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                #region 添加Post 参数
                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++;
                }
                JHLog.Instance().Writelog("builder:" + builder.ToString());
                byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                #endregion
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                   string result = reader.ReadToEnd();
                   JHLog.Instance().Writelog("响应内容:"+result);
                    return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("请求失败:{0}", ex.Message));
            }
        }


        /// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串  application/x-www-form-urlencoded
///using System.Net.Security;
///using System.Security.Cryptography.X509Certificates;
/// </summary> /// <param name="url">请求后台地址</param> /// <returns></returns> public string DicPosts(string url, Dictionary<string, string> dic) { string result = ""; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //一定要有这一句 ServicePointManager.ServerCertificateValidationCallback = delegate( Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return (true); }; req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; #region 添加Post 参数 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++; } byte[] data = Encoding.UTF8.GetBytes(builder.ToString()); req.ContentLength = data.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } #endregion HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream stream = resp.GetResponseStream(); //获取响应内容 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } return result; } /// <summary> /// POST请求与获取结果 /// 地址:http://ip:port?appid=11&dd=22&appkey=33 /// </summary> public string HttpPostJson(string Url, string postDataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/json"; // request.ContentLength = postDataStr.Length; StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.GetEncoding("utf-8")); writer.Write(postDataStr); writer.Flush(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string encoding = response.ContentEncoding; if (encoding == null || encoding.Length < 1) { encoding = "UTF-8"; //默认编码 } StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding)); string retString = reader.ReadToEnd(); return retString; }

  

posted on 2022-06-07 16:00  梦想&现实  阅读(363)  评论(0编辑  收藏  举报