How to POST request in c# with content-type being x-www-form-urlencoded?

和自甴很熟 提交于 2020-01-06 19:53:24

问题


Picture of Postman POST request

I would like to make this POST request to receive an OAuth2 access token but using c# code in Visual Studio 2015.

Thanks.


回答1:


System.Net.HttpWebRequest is the class you need to know, this is a easy sample. About more infomation see 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()


来源:https://stackoverflow.com/questions/41970659/how-to-post-request-in-c-sharp-with-content-type-being-x-www-form-urlencoded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!