C# POST application/x-www-form-urlencoded 请求

/// <summary>
        /// Post as x-www-form-urlencoded
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="data">"a=1&b=2" - 请求参数格式</param>
        public string HttpPostAsXWWWFormUrlEncoded(string data, string url)
        {
            string result = "";
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.AllowAutoRedirect = true;
                request.Timeout = 20 * 1000;
                request.ContentType = "application/x-www-form-urlencoded";
                var byteArray = Encoding.Default.GetBytes(data);
                request.ContentLength = byteArray.Length;
                using (var newStream = request.GetRequestStream())
                {
                    newStream.Write(byteArray, 0, byteArray.Length);
                    newStream.Close();
                }

                var response = (HttpWebResponse)request.GetResponse();
                var rspStream = response.GetResponseStream();
                using (var reader = new StreamReader(rspStream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                    rspStream.Close();
                }
                response.Close();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return result;
        }

调用方式:

var data = $"rdid={userBarcode}&password={userPassword}&barcode={patronBarcode}";
var response = HttpPostAsXWWWFormUrlEncoded(data, $"http://localhost/opac/api/reservation/addReservation");

posted @ 2022-04-13 14:37  SilverFox8588  阅读(3182)  评论(0编辑  收藏  举报