FormUrlEncodedContent 和查询字符串有什么区别?

der*_*vil 2 c# httpclient

我正在使用以下方法进行一些网络抓取

这对大多数网站都是成功的。

var content = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("v1", "value1"),
    new KeyValuePair<string, string>("v2", "value2"),
    new KeyValuePair<string, string>("v3", "value3"),
});
var response = await client.PostAsync("http://url.com", content);
html = await response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)

有时某些网站需要这种方式来获得响应。

var url = "http://url.com?v1=value1&v2=value2&v3=value3";
var response = await client.PostAsync(url, null);
html = await response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)

有时需要这个才能得到回应。

var query = "v1=value1&v2=value2&v3=value3";
var content = new ByteArrayContent(Encoding.UTF8.GetBytes(query));
var response = await client.PostAsync("http://url.com", content);
html = await response.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)

我真的不知道有什么区别。

Dzi*_*nis 5

如果您使用FormUrlEncodedContent您的参数将在请求正文中发送并格式化为查询字符串。

POST http://url.com/ HTTP/1.1
Host: url.com
Content-Length: 29
Expect: 100-continue
Connection: Keep-Alive

v1=value1&v2=value2&v3=value3 
Run Code Online (Sandbox Code Playgroud)

在第二种情况下,参数将作为 URL 的查询部分发送。

POST http://url.com/?v1=value1&v2=value2&v3=value3 HTTP/1.1
Host: url.com
Content-Length: 0 
Run Code Online (Sandbox Code Playgroud)

在第三种情况下,您query在请求正文中发送了内容。

在您的示例中具有与第一种情况相同的效果,但您手动进行了格式化。