11

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
McDee
  • 142
  • 1
  • 2
  • 10

3 Answers3

12

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.

Kyeotic
  • 19,697
  • 10
  • 71
  • 128
  • I almost forgot to tell you that the link I need to access requires login using user name and password. How do I incorporate that in this code? – McDee Dec 21 '11 at 19:23
  • Here is what I am doing right now using the browser. Page 1 : Enter Login Info. Press Submit Page 2 : has 2 frames. In top frame, I enter email address and click on Load Records. This populates all the info in the bottom frame 2. – McDee Dec 21 '11 at 20:52
  • i need help that i also want to transfer my data like firstname to http://eservice.dohms.gov.ae/pservices/CreatePID0.aspx given website. is is possible ?? – Bhupendra Jul 05 '14 at 06:38
3

MSDN has a great article with step-by-step instructions detailing how you can use the WebRequest class to send data. Link below:

http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

Phil Klein
  • 7,344
  • 3
  • 30
  • 33
1

Yes, there is a WebClient class. Look into documentation. There're some usful method to make GET and POST requests.

Wojteq
  • 1,173
  • 9
  • 23