You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.Net HttpClient中如何设置Content-Type为application/x-www-form-urlencoded?

问题解决:设置application/x-www-form-urlencoded Content-Type报错

错误原因

Content-Type属于内容头,而非请求级别的头部,必须绑定到HttpContent对象上,不能直接添加到HttpRequestMessage.Headers集合中,这就是错误提示的核心原因。

解决方法

方法1:使用FormUrlEncodedContent(推荐)

该类会自动设置正确的Content-Type头,同时方便构造表单参数:

using (var httpClient = new HttpClient())
{
    // 构造表单参数(根据接口需求添加,无参数可留空)
    var formParams = new Dictionary<string, string>
    {
        // {"paramName", "paramValue"}
    };

    var request = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        RequestUri = new Uri(path),
        // 用FormUrlEncodedContent作为请求内容,自动携带Content-Type
        Content = new FormUrlEncodedContent(formParams)
    }; 

    request.Headers.Add("Accept", "application/json");

    HttpResponseMessage response1 = await httpClient.SendAsync(request);
    var token = await response1.Content.ReadAsStringAsync();
}

方法2:手动为HttpContent设置Content-Type头

如果接口仅需要该头而无需请求体,可手动创建空内容并设置头:

using (var httpClient = new HttpClient())
{
    var request = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        RequestUri = new Uri(path),
        Content = new StringContent(string.Empty) // 空请求内容
    }; 

    request.Headers.Add("Accept", "application/json");
    // 为内容对象设置Content-Type头
    request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

    HttpResponseMessage response1 = await httpClient.SendAsync(request);
    var token = await response1.Content.ReadAsStringAsync();
}

内容的提问来源于stack exchange,提问作者Niranga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 04:18:21