C# Post封装

 public static string PostRequest(string postUrl, string paramData)
    {
        string ret = string.Empty;
        try
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
            webReq.Method = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.ContentLength = byteArray.Length;
            Stream newStream = webReq.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);//写入参数
            newStream.Close();
            try
            {
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                var c = response.GetResponseStream();
                StreamReader sr = new StreamReader(c, Encoding.UTF8);
                while (sr.Peek() > 0)
                {
                    Char[] read = new Char[256];
                    int count = sr.Read(read, 0, read.Length);

                    String str = new String(read, 0, count);

                    ret += str;
                }

                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (WebException ex)
            {
                //如果服务器报错(如字段不存在等异常),报500错误,此处进行获取提示信息
                var res = (HttpWebResponse)ex.Response;
                StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd();
            }
        }
        catch (Exception ex)
        {

        }
        return ret;
    }

 

posted @ 2021-12-24 17:32  极客船长  阅读(230)  评论(0编辑  收藏  举报