简体   繁体   English

在WinRT HttpClient上设置请求Content-Type

[英]Set request Content-Type on WinRT HttpClient

I'm developing a Windows 8.1 Store apps with C# and .NET Framework 4.5.1. 我正在使用C#和.NET Framework 4.5.1开发Windows 8.1 Store应用程序。

I'm trying to do a POST to a REST API but I get an Unsupported Media Type with this code: 我正在尝试对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;
}

If I change this line: 如果我更改此行:

response = await httpClient.PostAsync(resourceUri, new HttpStringContent(jsonContent));

With this one: 有了这个:

response = await httpClient.PostAsync(resourceUri, new HttpStringContent(string.Empty));

It works. 有用。 I don't get 415 status code. 我没有得到415状态代码。

jsonContent value is: jsonContent值为:

{"UserName":"My Name","Provider":"Facebook","ExternalAccessToken":"Access token omitted"}

Because I haven't found any similar code on Internet, and I only have 4 views on this question; 因为我没有在Internet上找到任何类似的代码,所以在这个问题上我只有4个观点。 I will share the answer. 我将分享答案。

I have fixed this problem changing the post with this code: 我已经解决了使用以下代码更改帖子的问题:

response = await httpClient.PostAsync(resourceUri,
    new HttpStringContent(jsonContent, UnicodeEncoding.Utf8, "application/json"));

You can pass "Content-Type" on HttpStringContent constructor. 您可以在HttpStringContent构造函数上传递“ Content-Type”。 More info here . 更多信息在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM