1

I basically have some idea how to use HttpWebRequests but I am pretty newbie. So I want to submit the following token with the Post method.

authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D&question%5Bquestion_text%5D=TEST+TEST+TEST&authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D 

What it does is click a button and send the text "TEST TEST TEST", this is the token I am getting from firebug when I click the button I want to.

2 Answers 2

1

To send some data with a Http Post Request you can try using the following code:

check 'var serverResponse' for server response.

 string targetUrl = "http://www.url.url"; var postBytes = Encoding.Default.GetBytes(@"authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D&question%5Bquestion_text%5D=TEST+TEST+TEST&authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D"); var httpRequest = (HttpWebRequest)WebRequest.Create(targetUrl); httpRequest.ContentLength = postBytes.Length; httpRequest.Method = "POST"; using (var requestStream = httpRequest.GetRequestStream()) requestStream.Write(postBytes, 0, postBytes.Length); var httpResponse = httpRequest.GetResponse(); using (var responseStream = httpResponse.GetResponseStream()) if (responseStream != null) using (var responseStreamReader = new StreamReader(responseStream)) { var serverResponse = responseStreamReader.ReadToEnd(); } 
Sign up to request clarification or add additional context in comments.

2 Comments

On line using (var requestStream = httpRequest.GetRequestStream()) i get this error: Cannot send a content-body with this verb-type.
my bad, I forgot to set httpRequest.Method to POST, see updated code.
1

Yet another solution:

// you can get the correct encoding from your site's response headers Encoding encoding = Encoding.UTF8; string targetUrl = "http://example.com"; var request = (HttpWebRequest)WebRequest.Create(targetUrl); var formData = new Dictionary<string, object>(); formData["authenticity_token"] = "pkhn7pwt3QATOpOAfBERZ+RIJ7oBEqGFpnF0Ir4RtJg="; formData["question[question_text]"] = "TEST TEST TEST"; bool isFirstField = true; StringBuilder query = new StringBuilder(); foreach (KeyValuePair<string, object> field in formData) { if (!isFirstField) query.Append("&"); else isFirstField= false; query.AppendFormat("{0}={1}", field.Key, field.Value); } string urlEncodedQuery = Uri.EscapeDataString(query.ToString()); byte[] postData = encoding.GetBytes(urlEncodedQuery); request.ContentLength = postData.Length; request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; using (BinaryWriter bw = new BinaryWriter(request.GetRequestStream())) bw.Write(postData); var response = request.GetResponse() as HttpWebResponse; // TODO: process response 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.