在WinRT HttpClient上设置请求内容类型
本文关键字:类型 请求 设置 WinRT HttpClient | 更新日期: 2023-09-27 18:29:00
我正在用C#和.NET Framework 4.5.1开发Windows 8.1 Store应用程序。
我正在尝试对REST API进行POST,但我得到了一个不支持的媒体类型,代码为:
public async Task<HttpResponseMessage> POST(string url, string jsonContent)
{
Uri resourceUri;
resourceUri = ValidateUri(url);
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
HttpRequestHeaderCollection headers = httpClient.DefaultRequestHeaders;
// Try to add user agent to headers.
if (headers.UserAgent.TryParseAdd(_userAgent))
headers.UserAgent.ParseAdd(_userAgent);
// Add Content-Type and Content-Length headers
headers.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
response = await httpClient.PostAsync(resourceUri, new HttpStringContent(jsonContent));
return response;
}
如果我更改此行:
response = await httpClient.PostAsync(resourceUri, new HttpStringContent(jsonContent));
有了这个:
response = await httpClient.PostAsync(resourceUri, new HttpStringContent(string.Empty));
它有效。我没有415状态码。
jsonContent
值为:
{"UserName":"My Name","Provider":"Facebook","ExternalAccessToken":"Access token omitted"}
因为我在网上没有找到类似的代码,我对这个问题只有4种看法;我将分享答案。
我已经解决了这个问题,用这个代码更改帖子:
response = await httpClient.PostAsync(resourceUri,
new HttpStringContent(jsonContent, UnicodeEncoding.Utf8, "application/json"));
您可以在HttpStringContent
构造函数上传递"内容类型"。点击此处了解更多信息。