阅读和使用C#发布到网页 [英] Reading and posting to web pages using C#
问题描述
我在工作中需要我能够将信息输入到一个网页,阅读下一页我重定向到,然后采取进一步行动的项目。一个简化的真实世界的例子是像去google.com,进入编码技巧作为搜索条件,然后阅读结果的页面。
I have a project at work the requires me to be able to enter information into a web page, read the next page I get redirected to and then take further action. A simplified real-world example would be something like going to google.com, entering "Coding tricks" as search criteria, and reading the resulting page.
之类的小编码实例的那些挂在 http://www.csharp-station.com/HowTo/HttpWebFetch。 ASPX 告诉如何阅读网页,而不是如何通过提交信息到一个窗体,并继续到下一个页面进行操作。
Small coding examples like the ones linked to at http://www.csharp-station.com/HowTo/HttpWebFetch.aspx tell how to read a web page, but not how to interact with it by submitting information into a form and continuing on to the next page.
有关记录,我不是建立一个恶意的和/或垃圾邮件相关的产品。
For the record, I'm not building a malicious and/or spam related product.
那么,如何去阅读网页,需要正常浏览的几个步骤,以达到?第一个
So how do I go read web pages that require a few steps of normal browsing to reach first?
推荐答案
您可以通过编程方式创建一个HTTP请求和检索响应:
You can programmatically create an Http request and retrieve the response:
string uri = "http://www.google.com/search";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// encode the data to POST:
string postData = "q=searchterm&hl=en";
byte[] encodedData = new ASCIIEncoding().GetBytes(postData);
request.ContentLength = encodedData.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(encodedData, 0, encodedData.Length);
// send the request and get the response
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// Do something with the response stream. As an example, we'll
// stream the response to the console via a 256 character buffer
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
Char[] buffer = new Char[256];
int count = reader.Read(buffer, 0, 256);
while (count > 0)
{
Console.WriteLine(new String(buffer, 0, count));
count = reader.Read(buffer, 0, 256);
}
} // reader is disposed here
} // response is disposed here
当然,这段代码将因为谷歌使用GET,而不是帖子,搜索查询返回一个错误。
Of course, this code will return an error since Google uses GET, not POST, for search queries.
如果你正在处理此方法将工作与特定的网页,作为URL和POST数据基本上都是硬编码。如果你需要的东西,这是一个有点更有活力,你必须:
This method will work if you are dealing with specific web pages, as the URLs and POST data are all basically hard-coded. If you needed something that was a little more dynamic, you'd have to:
- 抢页
- 带出的形式
- 创建基于表单字段POST字符串
。FWIW,我认为像Perl或Python的可能更适合于那种任务
FWIW, I think something like Perl or Python might be better suited to that sort of task.
编辑:X WWW的形式进行了urlencoded
edit: x-www-form-urlencoded
这篇关于阅读和使用C#发布到网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!