如何将数据发布到网站 [英] How to post data to a website

查看:69
本文介绍了如何将数据发布到网站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将数据发布到网站.所以我在 C#.net 中创建了一个小应用程序,我打开这个网站并用我的数据库中的值填充所有控件(单选按钮、文本框、复选框等).我在提交按钮上也有一个点击事件.然后应用等待 10-15 秒,然后将响应从网页复制到我的数据库.

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.

如您所见,这确实是一个忙碌的过程.如果有数千条记录要上传,这个应用程序需要更长的时间(因为它等待响应 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).

还有其他方法可以发布数据吗?我正在寻找诸如将所有字段与其值连接起来并像数据流一样上传之类的东西.如果网站是 https 而不是 http,这将如何工作?

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?

推荐答案

您可以使用 HttpWebRequest 来执行此操作,您可以将要发布的所有值连接到请求的单个字符串中.它可能看起来像这样:

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();

此方法应该适用于 http 和 https.

This method should work fine for http and https.

这篇关于如何将数据发布到网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆