天天看點

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;
        }    
           

  

轉載于:https://www.cnblogs.com/a735882640/p/11049366.html