C# Http Post 请求

2020-01-15  本文已影响0人  我是Mr小赵先生

亲测可用

       public static string HttpPost(string url, string postDataStr)
        {
            return HttpPost(url, postDataStr, "application/json");
        }
        public static string HttpPost(string Url, string postDataStr, string contentType)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = contentType;

                byte[] postByte = Encoding.UTF8.GetBytes(postDataStr);
                request.ContentLength = postByte.Length;
                //request.ContentLength = postDataStr.Length;
                using (Stream stream=request.GetRequestStream())
                {
                    stream.Write(postByte, 0, postByte.Length);//把要上传网页系统的数据通过post发送
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response!= null && response.StatusCode == HttpStatusCode.OK)
                {
                    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();
                    response.Close();
                    return retString;
                }
                else
                {
                    response.Close();
                    return "";
                }
            }
            catch (Exception ex)
            {
                return "";
            }
        }
上一篇 下一篇

猜你喜欢

热点阅读