在 HttpClient 中传递 application/x-www-form-urlencoded 中的数据

Passing data in application/x-www-form-urlencoded in HttpClient

data : P1;P2
format : json

来自 POSTMAN 的相应 curl 代码

curl --location --request POST 'https://ap-url/id/' \
--header 'content-type: application/x-www-form-urlencoded' \
--data-urlencode 'data=P1;P2' \

如何在 HttpClient 上以 x-www-form-urlencoded 格式发送数据?

  1. https://curl.olsh.me/ 用于 C# 代码的 curl 命令
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);
    }
}

最好的模式是设置一个字典并在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));