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





