我正在使用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"}
最佳答案
因为我没有在Internet上找到任何类似的代码,所以我对这个问题只有4个观点。我将分享答案。
我已经解决了使用以下代码更改帖子的问题:
response = await httpClient.PostAsync(resourceUri,
new HttpStringContent(jsonContent, UnicodeEncoding.Utf8, "application/json"));
您可以在
HttpStringContent
构造函数上传递“ Content-Type”。更多信息here。