如何在 C# 中模拟浏览器 HTTP POST 请求并捕获结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2071321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to simulate browser HTTP POST request and capture result in C#
提问by Peter Stegnar
Lets say we have a web page with a search input form, which submits data to server via HTTP GET. So that's mean server receive search data through query strings. User can see the URL and can also initialize this request by himself (via URL + Query strings).
假设我们有一个带有搜索输入表单的网页,它通过 HTTP GET 向服务器提交数据。所以这意味着服务器通过查询字符串接收搜索数据。用户可以看到 URL,也可以自己初始化这个请求(通过 URL + Query 字符串)。
We all know that. Here is the question.
我们都知道。这是问题。
What if this web page submits data to the server via HTTP POST? How can user initialize this request by himself?
如果这个网页通过 HTTP POST 向服务器提交数据怎么办?用户如何自己初始化这个请求?
Well I know how to capture HTTP POST (that's why network sniffers are for), but how can I simulate this HTTP POST request by myself in a C# code?
好吧,我知道如何捕获 HTTP POST(这就是网络嗅探器的用途),但是我如何在 C# 代码中自己模拟这个 HTTP POST 请求?
采纳答案by Darin Dimitrov
You could take a look at the WebClientclass. It allows you to post data to an arbitrary url:
您可以查看WebClient类。它允许您将数据发布到任意网址:
using (var client = new WebClient())
{
var dataToPost = Encoding.Default.GetBytes("param1=value1¶m2=value2");
var result = client.UploadData("http://example.com", "POST", dataToPost);
// do something with the result
}
Will generate the following request:
将生成以下请求:
POST / HTTP/1.1
Host: example.com
Content-Length: 27
Expect: 100-continue
Connection: Keep-Alive
param1=value1¶m2=value2