简体   繁体   English

如何将数据发布到网站

[英]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. 所以我在C#.net中创建了一个小应用程序,在那里我打开这个网站,用我的数据库中的值填写所有控件(单选按钮,文本框,复选框等)。 I also have a click event on the SUBMIT button. 我还在SUBMIT按钮上有一个点击事件。 The app then waits for 10-15 seconds and then copies the response from the webpage to my database. 然后应用程序等待10-15秒,然后将响应从网页复制到我的数据库。

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). 如果要上传数千条记录,这个应用程序需要更长的时间(因为它等待响应的时间为15秒)。

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? 如果网站是https而不是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. 您可以使用HttpWebRequest执行此操作,并且可以将要发布的所有值连接到请求的单个字符串中。 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. 此方法应适用于http和https。

MSDN has a great article with step-by-step instructions detailing how you can use the WebRequest class to send data. MSDN有一篇很棒的文章,其中包含详细说明如何使用WebRequest类发送数据的分步说明。 Link below: 下方链接:

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

Yes, there is a WebClient class. 是的,有一个WebClient类。 Look into documentation . 查看文档 There're some usful method to make GET and POST requests. 有一些usful方法来发出GET和POST请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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