8

I am trying to use HttpClient's PostAsync to login to a website; However it always fails and when I tracked the connection using WireShark I found that it posts the data incorrectly

Code

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

or

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)
};

usage

httpClient.PostAsync(postUri, content)

Expectations

value1=123456&value2=123456&value3=123456

Reality

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

3 回答 3

4

我知道这有效:

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)
}
于 2013-07-31T15:10:34.713 回答
1

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

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())
};
于 2013-07-31T15:16:17.170 回答
0

在我看来,这更好看:

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

并且字典可用于在加载时检查重复值,除非您需要重复键...

于 2017-07-20T03:13:52.160 回答