【问题标题】:Passing data in application/x-www-form-urlencoded in HttpClient在 HttpClient 中的 application/x-www-form-urlencoded 中传递数据
【发布时间】:2020-06-29 20:40:55
【问题描述】:
- 将来自 POSTMAN 的数据作为 x-www-form-urlencoded 传递
- 键值如下:
数据:P1;P2
格式:json
来自 POSTMAN 的相应 curl 代码
curl --location --request POST 'https://ap-url/id/' \
--header '内容类型:应用程序/x-www-form-urlencoded' \
--data-urlencode '数据=P1;P2' \
如何在 HttpClient 上以 x-www-form-urlencoded 格式发送数据?
【问题讨论】:
标签:
asp.net-core
httpclient
x-www-form-urlencoded
【解决方案1】:
- 使用 https://curl.olsh.me/ 将 curl 命令用于 C# 代码
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api-url/id"))
{
var contentList = new List<string>();
contentList.Add($"data={Uri.EscapeDataString("P1;P2")}");
contentList.Add($"format={Uri.EscapeDataString("json")}");
request.Content = new StringContent(string.Join("&", contentList));
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded");
var response = await httpClient.SendAsync(request);
}
}
【解决方案2】:
最好的Pattern是设置一个字典,在post方法中发送这个字典数据
var client = _clientFactory.CreateClient("mobile-server");
var data = new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id",
_configuration.GetValue<string>("MobileTop:ClientId")),
new KeyValuePair<string, string>("client_secret",
_configuration.GetValue<string>("MobileTop:ClientSecret")),
};
var response =
await client.PostAsync("api/v2/connect/token", new FormUrlEncodedContent(data));