C#post请求(application/x-www-form-urlencoded)
1.引用
//发送的参数
string url = " ";
model1 user = new model1();
user.id = " ";
user.name = " ";
var strPostData = ToPaeameter(user);
var strResponse = PostUrl(url, strPostData);
Token usermodel = JsonConvert.DeserializeObject<Token>(strResponse);
2.方法
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('&');
}