C# POST请求 json格式

时间:2025-03-12 07:38:35

    /*
    *  url:POST请求地址,例如:url = "http://localhost:8089/hal/PostData";
    *  postData:json格式的请求报文,例如:{"key1":"value1","key2":"value2"}
    */

        public static string JsonPostUrl(string url, string postData)
        {
            string result = "";
            try
            {
                HttpWebRequest req = (HttpWebRequest)(url);

                = "POST";

                // = "800";//设置请求超时时间,单位为毫秒

                = "application/json";

                byte[] data = Encoding.(postData);

                = ;

                using (Stream reqStream = ())
                {
                    (data, 0, );

                    ();
                }

                HttpWebResponse resp = (HttpWebResponse)();

                Stream stream = ();

                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = ();
                }

                return result;
            }
            catch (Exception ex)
            {
                result = "";
                ("POST异常错误", ex);
            }
            return "";
        }