我试图设置一个HttpClient对象的Content-Type头作为我调用的API所要求的。

我试着像下面这样设置内容类型:

using (var httpClient = new HttpClient())
{
    httpClient.BaseAddress = new Uri("http://example.com/");
    httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
    httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");
    // ...
}

它允许我添加Accept头,但当我尝试添加Content-Type时,它会抛出以下异常:

误用头名称。确保请求头与一起使用 HttpRequestMessage,带有HttpResponseMessage的响应头,以及 内容头与HttpContent对象。

如何在HttpClient请求中设置内容类型报头?


当前回答

好吧,它不是HTTPClient,但如果你能使用它,WebClient是相当简单的:

using (var client = new System.Net.WebClient())
 {
    client.Headers.Add("Accept", "application/json");
    client.Headers.Add("Content-Type", "application/json; charset=utf-8");
    client.DownloadString(...);
 }

其他回答

一些关于。net Core的额外信息(在阅读了erdomke关于设置私有字段以在没有内容的请求上提供内容类型的文章后)…

在调试我的代码之后,我无法通过反射看到要设置的私有字段-所以我想我应该尝试重新创建这个问题。

我使用。net 4.6尝试了以下代码:

HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Get, @"myUrl");
httpRequest.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json");

HttpClient client = new HttpClient();
Task<HttpResponseMessage> response =  client.SendAsync(httpRequest);  //I know I should have used async/await here!
var result = response.Result;

正如预期的那样,我得到了一个聚合异常,其内容为“无法发送具有此动词类型的内容体”。

然而,如果我用。net Core(1.1)做同样的事情-我不会得到异常。我的服务器应用程序非常高兴地回答了我的请求,并选择了内容类型。

我对此感到惊喜,我希望它能帮助到一些人!

为那些受困于字符集的人准备的

我有一个非常特殊的情况,服务提供商不接受字符集,他们拒绝改变子结构来允许它…… 不幸的是,HttpClient通过StringContent自动设置报头,不管你传递的是null还是Encoding。UTF8,它总是会设置字符集…

今天我在改变子系统的边缘;从HttpClient转向其他东西,我想到了一些东西…,为什么不用反射来清空“字符集”呢?... 在我尝试之前,我想到了一种方法,“也许我可以在初始化后改变它”,这是有效的。

下面是如何设置“application/json”头没有“;charset = utf - 8”。

var jsonRequest = JsonSerializeObject(req, options); // Custom function that parse object to string
var stringContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
stringContent.Headers.ContentType.CharSet = null;
return stringContent;

注意:下面的空值无效,加";charset = utf - 8”

return new StringContent(jsonRequest, null, "application/json");

EDIT

@DesertFoxAZ建议也可以使用下面的代码,工作良好。(没有自己测试,如果它的工作率,并在评论中赞扬他)

stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

对于我的场景,第三方API正在创建HttpRequestMessage,因此我无法使用投票最多的答案来解决这个问题。我不喜欢干扰反射的想法所以其他答案也不成立。

相反,我从AndroidMessageHandler扩展,并使用这个新类作为HttpClient的参数。AndroidMessageHandler包含SendAsync方法,可以在HttpRequestMessage对象发送之前重写该方法。如果您没有访问Android Xamarin库的权限,您可以使用HttpMessageHandler来解决一些问题。

public class XamarinHttpMessageHandler : global::Xamarin.Android.Net.AndroidMessageHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Here I make check that I'm only modifying a specific request
        // and not all of them.
        if (request.RequestUri != null && request.RequestUri.AbsolutePath.EndsWith("download") && request.Content != null)
        {
            request.Content.Headers.Add("Content-Type", "text/plain");
        }
        return base.SendAsync(request, cancellationToken);
    }
}

然后使用:

var client = new HttpClient(new XamarinHttpMessageHandler());

Api返回

"不支持的媒体类型","状态":415

添加ContentType到jsonstring做了魔法,这是我的脚本工作100%到今天为止

    using (var client = new HttpClient())
            {
                   var endpoint = "api/endpoint;
                    var userName = "xxxxxxxxxx";
                    var passwd = "xxxxxxxxxx";
                    var content = new StringContent(jsonString, Encoding.UTF8, "application/json");

                    var authToken = Encoding.ASCII.GetBytes($"{userName}:{passwd}");

                client.BaseAddress = new Uri("https://example.com/");

                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
            
                HttpResponseMessage response = await client.PostAsync(endpoint, content);

                if (response.IsSuccessStatusCode)
                {
                    // Get the URI of the created resource.
                    Uri returnUrl = response.Headers.Location;
                    Console.WriteLine(returnUrl);
                }
                string responseBody = await response.Content.ReadAsStringAsync();
                return responseBody;
        }

你需要这样做:

    HttpContent httpContent = new StringContent(@"{ the json string }");
    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                
    HttpResponseMessage message = client.PostAsync(@"{url}", httpContent).Result;