c#http请求

一、HttpWebRequest

 public string  Post(string url, string data) 
        {  
            Stream dataStream = null;
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            StreamReader reader = null;
            try
            {
                byte[] dataArray = Encoding.GetEncoding("utf-8").GetBytes(data);
                //创建请求
                request = (HttpWebRequest)HttpWebRequest.Create(url);

                request.Credentials = CredentialCache.DefaultCredentials;
                request.CookieContainer = new CookieContainer();
                request.Method = "POST";
                request.ContentType = "application/json";//访问规则
                request.ContentLength = dataArray.Length;//数据长度
                dataStream = request.GetRequestStream();
                dataStream.Write(dataArray, 0, dataArray.Length);
                response = (HttpWebResponse)request.GetResponse();//获取返回值
                reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                return reader.ReadToEnd();
            }
            catch (Exception ex)
            {
              
            }
            finally
            {
                if (reader != null)
                    reader.Close();
                if (response != null)
                    response.Close();
                if (dataStream != null)
                    dataStream.Close();
                if (request != null)
                    request.Abort();
            }

            return "";
        }

二、HttpClient

   public  string Post(string Url, List<KeyValuePair<string, string>> paramArray, string ContentType = "application/x-www-form-urlencoded", string authcode = "")
        {
            string result = "";
            var postData = BuildParam(paramArray);
            var data = Encoding.ASCII.GetBytes(postData);
            try
            {
                using (HttpClient http = new HttpClient())
                {
                    http.DefaultRequestHeaders.Add("User-Agent", @"Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)");
                    http.DefaultRequestHeaders.Add("Accept", @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                    HttpResponseMessage message = null;
                    using (Stream dataStream = new MemoryStream(data ?? new byte[0]))
                    {
                        using (HttpContent content = new StreamContent(dataStream))
                        {
                            content.Headers.Add("Content-Type", ContentType);
                            content.Headers.Add("auth_code", authcode);
                            var task = http.PostAsync(Url, content);
                            message = task.Result;
                        }
                    }
                    if (message != null && message.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        using (message)
                        {
                            result = message.Content.ReadAsStringAsync().Result;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return result;
        }

        private  string BuildParam(List<KeyValuePair<string, string>> paramArray, Encoding encode = null)
        {
            string url = "";

            if (encode == null) encode = Encoding.UTF8;

            if (paramArray != null && paramArray.Count > 0)
            {
                var parms = "";
                foreach (var item in paramArray)
                {
                    parms += string.Format("{0}={1}&", Encode(item.Key, encode), Encode(item.Value, encode));
                }
                if (parms != "")
                {
                    parms = parms.TrimEnd('&');
                }
                url += parms;

            }
            return url;
        }
        private static string Encode(string content, Encoding encode = null)
        {
            if (encode == null) return content;

            return System.Web.HttpUtility.UrlEncode(content, Encoding.UTF8);
        }

 

posted on 2024-02-05 09:46  棽犹  阅读(103)  评论(0编辑  收藏  举报

导航