本文介绍了HttpClient的PostAsync无效的帖子格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用的HttpClient的PostAsync登录到网站上;然而,它总是失败,当我跟踪使用Wireshark的我发现,它职位数据错误



连接

代码



  VAR内容=新FormUrlEncodedContent(新[] 
{
新KeyValuePair<字符串,字符串>(值1,数据1),
新KeyValuePair<字符串,字符串>(值2,数据2),
新KeyValuePair<字符串,字符串>(值3,数据3)
});

  VAR内容=新的List< KeyValuePair<字符串,字符串>> 
{
新KeyValuePair<字符串,字符串>(值1,数据1),
新KeyValuePair<字符串,字符串>(值2,数据2),
新KeyValuePair<字符串,字符串>(值3,数据3)
};



使用



  httpClient.PostAsync(定位PostURI,内容)



期望



 值1 = 123456&安培;数值2 = 123456&安培; VALUE3 = 123456 



现实



  //它增加了奇怪+ =这使得后失败... 
值1 = 123456&放大器;值2 + = 123456&放大器;值3 + = 123456


解决方案

我知道这个作品:

  VAR值=新的List< KeyValuePair<字符串,字符串>>(); 

values.Add(新KeyValuePair<字符串,字符串>(项目1,值1));
values.Add(新KeyValuePair<字符串,字符串>(项目2,值2));
values.Add(新KeyValuePair<字符串,字符串>(项目3,值3));

使用(VAR内容=新FormUrlEncodedContent(值))
{
client.PostAsync(定位PostURI,内容)。结果)
}


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 fails...
value1=123456&value2+=123456&value3+=123456
解决方案

I Know this works:

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

这篇关于HttpClient的PostAsync无效的帖子格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-14 12:36