How to add parameters into a WebRequest?

Quan Mai picture Quan Mai · Jul 19, 2010 · Viewed 180.9k times · Source

I need to call a method from a webservice, so I've written this code:

 private string urlPath = "http://xxx.xxx.xxx/manager/";
 string request = urlPath + "index.php/org/get_org_form";
 WebRequest webRequest = WebRequest.Create(request);
 webRequest.Method = "POST";
 webRequest.ContentType = "application/x-www-form-urlencoded";
 webRequest.
 webRequest.ContentLength = 0;
 WebResponse webResponse = webRequest.GetResponse();

But this method requires some parameters, as following:

Post data:

_username:'API USER',         // api authentication username

_password:'API PASSWORD',     // api authentication password

How can I add these parameters into this Webrequest?

Thanks in advance.

Answer

CoderHawk picture CoderHawk · Jul 19, 2010

Use stream to write content to webrequest

string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;  
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();