Cannot set Headers on HttpFormUrlEncodedContent

I am using Windows.Web.Http.HttpClient.SendRequestAsync and post HttpFormUrlEncodedContent with some custom headers.

When trying to:

HttpClient httpClient = new HttpClient();

IList<KeyValuePair<string, string>> requestData = new List<KeyValuePair<string, string>>();
requestData.Add(new KeyValuePair<string, string>("form", "content"));
HttpFormUrlEncodedContent request = new HttpFormUrlEncodedContent(requestData);

request.Headers.TryAppendWithoutValidation("Custom", "Header");

I get exception:

WinRT information: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.

How can I add per-request custom headers with HttpFormUrlEncodedContent?

Note, that while I know for HttpClient.DefaultRequestHeaders, it is not quite an option, because I'd like to reuse the HttpClient instance.


So you cannot actually set Headers to the Content itself. Turns out you need to wrap the HttpFormUrlEncodedContent in HttpRequestMessage and then set the headers to the HttpRequestMessage object like this:

HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(requestData);
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, ServiceUri);
req.Content = content;
req.Headers.Add("Custom", "Header");
链接地址: http://www.djcxy.com/p/46256.html

上一篇: 如何使用HttpClient在单个请求上设置HttpHeader

下一篇: 无法在HttpFormUrlEncodedContent上设置标题