• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#接口的Get、Post、WebService请求方法一览,值得收藏

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

C# 接口的Get、Post、WebService请求方法一览,值得收藏

public static class HttpHelper
    {
        const string DEFAULT_USER_AGENT = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 4.0.30319)";
        const string DEFAULT_CONTENT_TYPE = "application/json";

        #region Http Get Method
        /// <summary>
        /// GET请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string Get(string url)
        {
            return Get(url, null);
        }

        /// <summary>
        /// GET请求,可以添加自定义的Header信息
        /// </summary>
        /// <returns></returns>
        public static string Get(string url, IDictionary<string, string> headerList)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.UserAgent = DEFAULT_USER_AGENT;
            request.ContentType = DEFAULT_CONTENT_TYPE;
            if (headerList != null)
            {
                foreach (var header in headerList)
                {
                    request.Headers.Add(header.Key, header.Value);
                }
            }

            var responseStream = request.GetResponse().GetResponseStream();

            using (var reader = new StreamReader(responseStream))
            {
                var result = reader.ReadToEnd();

                responseStream.Close();

                return result;
            }
        }
        #endregion

        /// <summary>
        /// POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static string Post(string url, string postData, string contentType = DEFAULT_CONTENT_TYPE)
        {
            var webClient = new WebClient();
            webClient.Headers.Add("user-agent", DEFAULT_USER_AGENT);
            webClient.Headers.Add("Content-Type", contentType);
            byte[] sendData = Encoding.UTF8.GetBytes(postData);
            byte[] responseData = webClient.UploadData(url, "POST", sendData);
            return Encoding.UTF8.GetString(responseData);
        }

        /// <summary>
        /// POST请求,并可以传入Header信息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="headParams"></param>
        /// <returns></returns>
        public static string Post(string url, string postData, IDictionary<string, string> headParams)
        {
            var webClient = new WebClient();
            webClient.Headers.Add("user-agent", DEFAULT_USER_AGENT);
            webClient.Headers.Add("Content-Type", DEFAULT_CONTENT_TYPE);
            if (headParams != null && headParams.Count > 0)
            {
                foreach (var item in headParams)
                {
                    if (webClient.Headers.AllKeys.Contains(item.Key))
                    {
                        webClient.Headers.Remove(item.Key);
                    }
                    webClient.Headers.Add(item.Key, item.Value);
                }
            }

            byte[] sendData = Encoding.UTF8.GetBytes(postData);
            byte[] responseData = webClient.UploadData(url, "POST", sendData);
            return Encoding.UTF8.GetString(responseData);
        }

        /// <summary>
        /// HTTP Post请求,可以传入Header信息和超时限制
        /// </summary>
        /// <param name="url"></param>
        /// <param name="content"></param>
        /// <param name="headParams"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static string HttpPost(string url, string content,string ContentType, IDictionary<string, string> headParams,int timeout)
        {
            try
            {
                string result = string.Empty;
               
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = ContentType;
                if (headParams != null && headParams.Count > 0)
                {
                    foreach (var item in headParams)
                    {
                        if (req.Headers.AllKeys.Contains(item.Key))
                        {
                            req.Headers.Remove(item.Key);
                        }
                        req.Headers.Add(item.Key, item.Value);
                    }
                }

                byte[] data = Encoding.UTF8.GetBytes(content);
                req.ContentLength = data.Length;
                req.Timeout = timeout * 1000;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 需要WebService支持Get调用
        /// </summary>
        public static string WebServiceGet(String url, String methodname, Hashtable pars)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url + "/" + methodname + "?" + HashtableToPostData(pars));
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded";
            // 凭证
            request.Credentials = CredentialCache.DefaultCredentials;
            //超时时间
            request.Timeout = 10000;
            var response = request.GetResponse();
            var stream = response.GetResponseStream();
            StreamReader sr = new StreamReader(stream, Encoding.UTF8);
            String retXml = sr.ReadToEnd();
            sr.Close();
            return retXml;
        }
       
        /// <summary>
        /// 需要WebService支持Post调用
        /// </summary>
        public static string PostWebServiceByJson(String url, String methodname, Hashtable pars)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url + "/" + methodname);
            request.Method = "POST";
            request.ContentType = "application/json;charset=utf-8";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Timeout = 10000;
            byte[] data = Encoding.UTF8.GetBytes(HashtableToPostData(pars));
            request.ContentLength = data.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(data, 0, data.Length);
            writer.Close();

            StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8);
            string retXml = sr.ReadToEnd();
            sr.Close();
            return retXml;
        }

        /// <summary>    
        /// http Post调用  WebService  
        /// </summary>    
        public static XmlDocument QueryPostWebService(String URL,
            String MethodName, Hashtable Pars) {

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.Timeout = 10000;
            #region 参数拼接成字符串,最后编码
            StringBuilder sb = new StringBuilder();
            foreach (string k in Pars.Keys) {
                if (sb.Length > 0) {
                    sb.Append("&");
                }
                sb.Append(
                    HttpUtility.UrlEncode(k) + "="
                    + HttpUtility.UrlEncode(Pars[k].ToString())
                    );
            }
            byte[] data = Encoding.UTF8.GetBytes(sb.ToString());
            #endregion
            #region  把编码后的参数写入请求流中
            request.ContentLength = data.Length;
            Stream writer = request.GetRequestStream();
            writer.Write(data, 0, data.Length);
            writer.Close();
            #endregion
            #region 读取结果,创建XmlDocument对象,对象加载结果
            var response = request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            String retXml = sr.ReadToEnd();
            sr.Close();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(retXml);
            #endregion
            return doc;
        }

        private static String HashtableToPostData(Hashtable ht)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string k in ht.Keys)
            {
                if (sb.Length > 0)
                {
                    sb.Append("&");
                }
                sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(ht[k].ToString()));
            }
            return sb.ToString();
        } 
        
    }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#中的函数(三)参数传递及返回值发布时间:2022-07-13
下一篇:
C#7.0核心技术指南原书第7版.pdf-分享-下载发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap