欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.NET MVC后台发送post请求

程序员文章站 2022-10-06 17:34:52
一、WebRequest方式 ......

一、WebRequest方式

  

//设置请求接口
var request = (HttpWebRequest)WebRequest.Create("http://xxx.com/xxx");
//请求参数
var postData = string.Format("appId={0}&appScreat={1}&channel={2}", appId, appScreat, channel);
var data = Encoding.ASCII.GetBytes(postData);
//请求方式
request.Method = "POST";
//请求头参数设置
request.Headers.Add("sign", sign);
request.Headers.Add("timestamp", timestamp);
request.Headers.Add("token", token);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}
//结果返回
var response = (HttpWebResponse)request.GetResponse();
//转字符串
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
//转换为json对象
MXCZUserInfoResponse userInfoResponse = JsonConvert.DeserializeObject<MXCZUserInfoResponse>(responseString);