Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post data to a website

Tags:

c#

http-post

web

I need to post data to a website. So I created a small app in C#.net where I open this website and fill in all the controls (radio buttons, text boxes, checkboxes etc) with the values from my database. I also have a click event on the SUBMIT button. The app then waits for 10-15 seconds and then copies the response from the webpage to my database.

As you can see, this is really a hectic process. If there are thousands of records to upload, this app takes much longer (due to fact that it waits 15s for the response).

Is there any other way to post data? I am looking for something like concatenating all the fields with its value and uploading it like a stream of data. How will this work if the website is https and not http?

like image 770
McDee Avatar asked Dec 16 '11 18:12

McDee


1 Answers

You can use HttpWebRequest to do this, and you can concatenate all the values you want to post into a single string for the request. It could look something like this:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.yoursite.com");
request.Method = "POST";

formContent = "FormValue1=" + someValue +
    "&FormValue2=" + someValue2 +
    "&FormValue=" + someValue2;

byte[] byteArray = Encoding.UTF8.GetBytes(formContent);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = HttpUtility.UrlDecode(reader.ReadToEnd());
//You may need HttpUtility.HtmlDecode depending on the response

reader.Close();
dataStream.Close();
response.Close();

This method should work fine for http and https.

like image 74
Kyeotic Avatar answered Nov 04 '22 17:11

Kyeotic