您可以以编程方式创建 Http 请求并检索响应:
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
当然,此代码将返回错误,因为 Google 使用 GET 而不是 POST 进行搜索查询。
如果您正在处理特定的网页,则此方法将起作用,因为 URL 和 POST 数据基本上都是硬编码的。如果你需要一些更有活力的东西,你必须:
- 捕获页面
- 去掉表格
- 根据表单字段创建 POST 字符串
FWIW,我认为 Perl 或 Python 之类的东西可能更适合这类任务。
编辑:x-www-form-urlencoded