HttpClient PostAsync后置格式无效

我正尝试使用HttpClient的PostAsync登录到网站; 然而,它总是失败,当我使用WireShark跟踪连接时,我发现它错误地发布了数据

var content = new FormUrlEncodedContent(new[] 
{
    new KeyValuePair<string, string>("value1", data1),
    new KeyValuePair<string, string>("value2", data2),
    new KeyValuePair<string, string>("value3", data3)
});

要么

var content = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("value1", data1), 
    new KeyValuePair<string, string>("value2", data2), 
    new KeyValuePair<string, string>("value3", data3)
};

用法

httpClient.PostAsync(postUri, content)

期望

value1=123456&value2=123456&value3=123456

现实

//It adds strange += which makes the post fail...
value1=123456&value2+=123456&value3+=123456

我知道这个作品:

var values = new List<KeyValuePair<string, string>>();

values.Add(new KeyValuePair<string, string>("Item1", "Value1"));
values.Add(new KeyValuePair<string, string>("Item2", "Value2"));
values.Add(new KeyValuePair<string, string>("Item3", "Value3"));

using (var content = new FormUrlEncodedContent(values))
{
    client.PostAsync(postUri, content).Result)
}

修剪可能的空白参数。 空格导致+

var content = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("value1", data1.Trim()), 
    new KeyValuePair<string, string>("value2", data2.Trim()), 
    new KeyValuePair<string, string>("value3", data3.Trim())
};

在我看来这更好看:

var variables = new Dictionary<string, string>() {
    { "value1", value1 },
    { "value2", value2 }
};
var content = new FormUrlEncodedContent(variables);

和一个字典可以用于检查加载它时重复的值,除非你需要重复的键...

链接地址: http://www.djcxy.com/p/73113.html

上一篇: HttpClient PostAsync Invalid Post Format

下一篇: Escape spaces in File Path