封装GET、POST请求

 /// <summary>
        /// HTTP请求方式枚举
        /// </summary>
        public enum HttpMethod { POST, GET };


                /// <summary>
        /// http请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="type">GET POST</param>
        /// <param name="ht"></param>
        /// <param name="encoder">编码默认UTF-8</param>
        /// <returns></returns>
        public static string HttpGet(string url, string type = "GET", Hashtable ht = null, Encoding encoder = null)
        {
            if (encoder == null) { encoder = Encoding.UTF8; }
            string sendData = string.Empty;
            if (ht != null && ht.Count > 0)
            {
                foreach (DictionaryEntry item in ht)
                {
                    sendData += item.Key + "=" + item.Value + "&";
                }
                sendData = sendData.TrimEnd('&');
            }


            if (type.ToUpper() == "GET")
            {
                if (sendData.Length > 1)
                    url += (url.IndexOf("?") > -1 ? "&" : "?") + sendData;
            }


            string readStr = string.Empty;
            try
            {
                HttpWebRequest http = (HttpWebRequest)WebRequest.Create(url);
                http.Method = type;
                http.Accept = "text/html, application/xhtml+xml, */*";
                //Encoding encoder = Encoding.GetEncoding("UTF-8");
                if (type.ToUpper() == "POST")
                {
                    http.ContentType = "application/x-www-form-urlencoded";
                    if (sendData.Length > 1)
                    {
                        byte[] buffer = encoder.GetBytes(sendData);
                        http.ContentLength = buffer.Length;
                        http.GetRequestStream().Write(buffer, 0, buffer.Length);
                    }
                }
                Stream strame = http.GetResponse().GetResponseStream();
                using (StreamReader read = new StreamReader(strame, encoder))
                {
                    readStr = read.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                readStr = "{\"msg\":\"HTTP错误,请检查访问接口!" + ex.Message + "\",\"stats\":-1,\"status\":-1}";
            }
            return readStr;
        }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值