如何在.Net httpClient中添加“application/x-www-form-urlencoded”作为内容类型

r3i60tvu  于 2023-02-20  发布在  .NET
关注(0)|答案(2)|浏览(222)

我无法添加内容类型为“application/x-www-form-urlencoded”。有抛出错误。仅适用于此内容类型。谢谢您的关注。

using (var httpClient = new HttpClient())
{
    var request = new HttpRequestMessage
    {
        Method = new HttpMethod("POST"),
        RequestUri = new Uri(path),
    }; 

    request.Headers.Add("Accept", "application/json");
    request.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

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

它会抛出这样的错误
标头名称"Content-Type“使用不当。请确保请求标头与HttpRequestMessage一起使用,响应标头与HttpResponseMessage一起使用,内容标头与HttpContent对象一起使用。

gdrx4gfi

gdrx4gfi1#

内容类型是内容的标头,而不是请求的标头,这就是失败的原因。

一种方法是调用TryAddWithoutValidation而不是add,如下所示:

request.Headers.TryAddWithoutValidation("Accept", "application/json");
request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");

另一种方法是您可以在创建请求内容本身时设置Content-Type,请参阅this answer

ql3eal8s

ql3eal8s2#

我用了更复杂的东西,但它的工作。

var client = new HttpClient();
        //headers dictionary
        var dict = new Dictionary<string, string>();
        dict.Add("Content-Type", "application/x-www-form-urlencoded");
        //request
        var req = new HttpRequestMessage(HttpMethod.Post, new Uri(url)) { Content = new FormUrlEncodedContent(dict) };
        req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencode"));
        var response = await client.SendAsync(req);

相关问题