c#Post方法封装处理

public static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
        {
            string ret = string.Empty;
            try
            {
                if (dataEncode == null)
                    dataEncode = Encoding.UTF8;

                byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
                //webReq.ContentType = "application/json; charset=UTF-8";


                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)
            {
                throw;
            }
            return ret;
        }    

  

posted @ 2019-06-19 09:02  735882640  阅读(664)  评论(0编辑  收藏  举报