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