如何在内容类型为x-www-form-urlencoded的情况下在c#中发送请求?

时间:2017-02-01 01:50:02

标签: c# oauth-2.0 http-post access-token postman

Picture of Postman POST request

我想发出此POST请求以接收OAuth2访问令牌,但在Visual Studio 2015中使用c#代码。

感谢。

1 个答案:

答案 0 :(得分:2)

System.Net.HttpWebRequest是您需要知道的课程,这是一个简单的示例。有关详细信息,请参阅MSDN:https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(v=vs.110).aspx

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.AllowAutoRedirect = true;
webRequest.Timeout = 20 * 1000;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36";


//write the data to post request
//Postdata : a=1&b=2&c=3
byte[] buffer = Encoding.Default.GetBytes(Postdata);
if (buffer != null)
{
     webRequest.ContentLength = buffer.Length;
     webRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
}

WebResponse wr = webRequest.GetResponse()