I'm trying to make web requests programmatically in ASP.NET, using the POST method.
I'd like to send POST parameters with the web request as well. Something like this:
WebRequest req = WebRequest.Create("accounts.craigslist.org/login/pstrdr"); req.Method = "POST"; req.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); //WebRequest.Parameters.add("areaabb","hou");
obviously the commented line does not work. How do I achieve this?
In a POST request, the parameters are sent as a body of the request, after the headers. To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.
Use [FromUri] attribute to force Web API to get the value of complex type from the query string and [FromBody] attribute to get the value of primitive type from the request body, opposite to the default rules.
You can pass parameters to Web API controller methods using either the [FromBody] or the [FromUri] attributes. Note that the [FromBody] attribute can be used only once in the parameter list of a method.
how to pass class parameter in Webrequest in C#. You need to send the class as object as a parameter in HttpWebRequest. Before sending the object we need to serialize it as a stream and then we able to send it.
Try like this...
string email = "YOUR EMAIL"; string password = "YOUR PASSWORD"; string URLAuth = "https://accounts.craigslist.org/login"; string postString = string.Format("inputEmailHandle={0}&name={1}&inputPassword={2}", email, password); const string contentType = "application/x-www-form-urlencoded"; System.Net.ServicePointManager.Expect100Continue = false; CookieContainer cookies = new CookieContainer(); HttpWebRequest webRequest = WebRequest.Create(URLAuth) as HttpWebRequest; webRequest.Method = "POST"; webRequest.ContentType = contentType; webRequest.CookieContainer = cookies; webRequest.ContentLength = postString.Length; webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"; webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; webRequest.Referer = "https://accounts.craigslist.org"; StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream()); requestWriter.Write(postString); requestWriter.Close(); StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()); string responseData = responseReader.ReadToEnd(); responseReader.Close(); webRequest.GetResponse().Close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With