• WPF HTTP请求(GET,POST)


    WPF HTTP请求(GET,POST)

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Nova.NovaiCloud.NovaiCloudCareHelper.Common
    {
        public class HttpRequestHelper
        {
            public static string HttpPost(string Url, string postDataStr,ref bool isSuccess)
            {
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                    request.Method = "POST";
                    request.ContentType = "application/json";
                    request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
                    //request.CookieContainer = cookie;
                    Stream myRequestStream = request.GetRequestStream();
                    StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
                    myStreamWriter.Write(postDataStr);
                    myStreamWriter.Close();
    
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
                    //response.Cookies = cookie.GetCookies(response.ResponseUri);
                    Stream myResponseStream = response.GetResponseStream();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                    string retString = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();
    
                    return retString;
                }
                catch (Exception e)
                {
                    isSuccess = false;
                    Console.Write(e.Message);
                    return e.Message;
                }
            }
    
            public string HttpGet(string Url, string postDataStr)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
                request.Method = "GET";
                request.ContentType = "application/json";
    
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
    
                return retString;
            }
    
            /// <summary>  
            /// 创建GET方式的HTTP请求  
            /// </summary>  
            //public static HttpWebResponse CreateGetHttpResponse(string url, int timeout, string userAgent, CookieCollection cookies)
            public static HttpWebResponse CreateGetHttpResponse(string url)
            {
                HttpWebRequest request = null;
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    //对服务端证书进行有效性校验(非第三方权威机构颁发的证书,如自己生成的,不进行验证,这里返回true)
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;    //http版本,默认是1.1,这里设置为1.0
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }
                request.Method = "GET";
    
                //设置代理UserAgent和超时
                //request.UserAgent = userAgent;
                //request.Timeout = timeout;
                //if (cookies != null)
                //{
                //    request.CookieContainer = new CookieContainer();
                //    request.CookieContainer.Add(cookies);
                //}
                return request.GetResponse() as HttpWebResponse;
            }
    
            /// <summary>  
            /// 创建POST方式的HTTP请求  
            /// </summary>  
            //public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies)
            public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters)
            {
                HttpWebRequest request = null;
                //如果是发送HTTPS请求  
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    //request.ProtocolVersion = HttpVersion.Version10;
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }
                request.Method = "POST";
                request.ContentType = "application/json";
    
                //设置代理UserAgent和超时
                //request.UserAgent = userAgent;
                //request.Timeout = timeout; 
    
                //if (cookies != null)
                //{
                //    request.CookieContainer = new CookieContainer();
                //    request.CookieContainer.Add(cookies);
                //}
                //发送POST数据  
                if (!(parameters == null || parameters.Count == 0))
                {
                    StringBuilder buffer = new StringBuilder();
                    int i = 0;
                    foreach (string key in parameters.Keys)
                    {
                        if (i > 0)
                        {
                            buffer.AppendFormat("&{0}={1}", key, parameters[key]);
                        }
                        else
                        {
                            buffer.AppendFormat("{0}={1}", key, parameters[key]);
                            i++;
                        }
                    }
                    byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }
                string[] values = request.Headers.GetValues("Content-Type");
                return request.GetResponse() as HttpWebResponse;
            }
    
            /// <summary>
            /// 获取请求的数据
            /// </summary>
            public static string GetResponseString(HttpWebResponse webresponse)
            {
                using (Stream s = webresponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(s, Encoding.UTF8);
                    return reader.ReadToEnd();
    
                }
            }
    
            /// <summary>
            /// 验证证书
            /// </summary>
            private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
            {
                if (errors == SslPolicyErrors.None)
                    return true;
                return false;
            }
        }
    }
    

      

  • 相关阅读:
    document.ready和window.onload的区别
    那些年,我们坚持着。
    JavaScript去除前后空格
    男孩的梦
    shapefile格式说明及读写代码示例 http://www.gispower.org/article/arcgis/arcother/2008/48/0848115049GB922C13K2I22H7G06A4.html
    如何在C#中加载自己编写的动态链接库(DLL)http://www.kehui.net/index.php/article/read/30/26323
    对象复制
    影像复制程序集在不关闭应用程序的前提下更新程序集
    ibatisnet系列(一) 总览 http://hjf1223.cnblogs.com/archive/2006/04/24/383118.html
    创建项模板模板参数
  • 原文地址:https://www.cnblogs.com/amwuau/p/7567656.html
Copyright © 2020-2023  润新知