C#psot请求(application/x-www-form-urlencoded)

本文详细介绍了如何在C#中使用POST请求发送application/x-www-form-urlencoded格式的数据。通过实例展示了如何创建HTTP请求,设置请求头,编码参数并发送请求,最后解析响应数据。

C#psot请求(application/x-www-form-urlencoded)

通过post请求application/x-www-form-urlencoded格式时可以使用PostUrl方式,传入api地址和同通过ToPaeameter方法拼接过的参数.
使用方式

 					userdata user= new userdata ();
                    user.id= "1";
                    user.name= "zhansan";
                    var Url = "https://open.ys7.com/api/lapp/device/camera/list";
                    strPostData = ToPaeameter(user);
                    strResponse = PostUrl(Url, strPostData);
                    userdata usermodel= JsonConvert.DeserializeObject<userdata >(strResponse);
        public string PostUrl(string url, string postData)
    {
        string result = "";
        try
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.Method = "POST";

            req.ContentType = "application/x-www-form-urlencoded";

            req.Timeout = 800;//请求超时时间

            byte[] data = Encoding.UTF8.GetBytes(postData);

            req.ContentLength = data.Length;

            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);

                reqStream.Close();
            }

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            Stream stream = resp.GetResponseStream();

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

        return result;
    }
/// <summary>
        /// 参数拼接Url
        /// </summary>
        /// <param name="source">要拼接的实体</param>
        /// <paramref name="IsStrUpper">是否开启首字母大写,默认小写</paramref>
        /// <returns>Url,</returns>
        public string ToPaeameter(object source)
        {
            var buff = new StringBuilder(string.Empty);
            if (source == null)
                throw new ArgumentNullException("source", "Unable to convert object to a dictionary. The source object is null.");
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(source))
            {
                object value = property.GetValue(source);
                if (value != null)
                {
                    buff.Append(WebUtility.UrlEncode(property.Name) + "=" + WebUtility.UrlEncode(value + "") + "&");
                }
            }
            return buff.ToString().Trim('&');
        }
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值