简体   繁体   中英

How to post data to a website

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM