C# HttpWebRequest of type “application/x-www-form-urlencoded” - how to send '&' character in content body?

C# HttpWebRequest of type “application/x-www-form-urlencoded” - how to send '&' character in content body?

First install "Microsoft ASP.NET Web API Client" nuget package:

  PM > Install-Package Microsoft.AspNet.WebApi.Client

Then use the following function to post your data:

public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
    using (var httpClient = new HttpClient())
    {
        using (var content = new FormUrlEncodedContent(postData))
        {
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            return await response.Content.ReadAsAsync<TResult>();
        }
    }
}

And this is how to use it:

TokenResponse tokenResponse = 
    await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);

or

TokenResponse tokenResponse = 
    (Task.Run(async () 
        => await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))
        .Result

or (not recommended)

TokenResponse tokenResponse = 
    PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;

 

可以参考的是FormUrlEncodedContent的使用,下面SendAsync是HttpClient的方法

复制代码
  var data = new Dictionary<string, string>
            {
                {"on", $"{false}"},
                {TokenHelper.TokenName, TokenHelper.TokenValue}
            };
            var content = new FormUrlEncodedContent(data);
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Patch,
                RequestUri = new Uri($"{_setupFixture.Client.BaseAddress}SelfRegistration/Switch"),
                Content = content
            };
            //request.Headers.Add(TokenHelper.TokenName, TokenHelper.TokenValue);
            //request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = await _setupFixture.Client.SendAsync(request);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
复制代码

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(1965)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2016-09-22 使用entityframework操作sqlite数据库
2016-09-22 excel在一个图表内,显示折线图和柱状图
2016-09-22 通过NuGet获取sqlite对应的.net的dll
2015-09-22 comparison of floating point numbers with equality operator. possible loss of precision while rounding values
2015-09-22 Formatting is Specified but argument is not IFormattable
2015-09-22 Covariance and Contravariance in C#的搜索条件
2015-09-22 Covariance and Contravariance in C#, Part Two: Array Covariance
点击右上角即可分享
微信分享提示