使用 HttpClient 将 Content-Type 设置为“application/json”并将对象添加到正文

Posted

技术标签:

【中文标题】使用 HttpClient 将 Content-Type 设置为“application/json”并将对象添加到正文【英文标题】:use HttpClient to set the Content-Type to "application/json" and add object to the body 【发布时间】:2019-01-31 22:41:02 【问题描述】:

我正在尝试使用 HttpClient 创建以下帖子,使用邮递员使其正常工作,但我似乎无法在代码中复制它。我需要将标头 Content-Type 设置为 application/json 并在帖子正文中有一个对象。

发布https://mycompanyurl.com/authenticate

标题 Key:Content-Type,Value:application/json

身体 “用户名”:“某个用户名”, “密码”:“某个密码”

using (var client = new HttpClient())

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

    var serializedObject = JsonConvert.SerializeObject(
                          new username = "username", password = "password" );
    var request = new HttpRequestMessage(HttpMethod.Post, "authenticate");
    request.Content = new StringContent(serializedObject, Encoding.UTF8,"application/json");                

    var response = await client.SendAsync(request);
    response.EnsureSuccessStatusCode();

    var content = await response.Content.ReadAsStringAsync();


使用 fidder 中的反向代理,我可以捕获来自邮递员的原始调用,该调用有效,其余 api 按预期返回结果:

POST http://127.0.0.1:8888/v1/authenticate HTTP/1.1 Content-Type: application/json;charset=UTF-8 cache-control: no-cache Postman-Token: 4db8f2dd-cbf0-413c-ad5b-20af0543a31d User-Agent: PostmanRuntime/7.6 .0 Accept: / Host: 127.0.0.1:8888 accept-encoding: gzip, deflate content-length: 87 Connection: keep-alive

"用户名":"用户名","密码":"密码"

我的来自 HttpClient 并使用 fiddler 的调用如下,这不起作用,返回 200 但它不能正常工作,没有返回数据,我看不到有效负载中的任何差异,这将使其余 api 无法按预期响应.

POST http://127.0.0.1:8888/v1/authenticate HTTP/1.1 Content-Type: application/json; charset=utf-8 Host: 127.0.0.1:8888 Content-Length: 87 Expect: 100-continue 连接: Keep-Alive

"用户名":"用户名","密码":"密码"

【问题讨论】:

欢迎来到 Stack Overflow!这里不完全清楚你在问什么样的问题。你有任何错误吗?代码的某些部分是否不起作用?请阅读how to ask 一个问题。 标头 Content-Type 为空,未设置 你检查过这个吗? ***.com/questions/35907642/… 【参考方案1】:

下面的逻辑应该生成与您的示例中提供的相同的工作请求签名(作为答案发布,请改为编辑您的问题),因此应该可以工作:

var clientHandler = new HttpClientHandler

    AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate,
    AllowAutoRedirect = false
;

using (var client = new HttpClient(clientHandler, true))

    client.BaseAddress = new Uri("http://127.0.0.1:8888/v1/");

    client.DefaultRequestHeaders.Add("cache-control", "no-cache");
    client.DefaultRequestHeaders.Add("Postman-Token", "db8f2dd-cbf0-413c-ad5b-20af0543a31d");
    client.DefaultRequestHeaders.Add("User-Agent", "PostmanRuntime/7.6.0");
    client.DefaultRequestHeaders.Add("Accept", "*/*");
    client.DefaultRequestHeaders.ExpectContinue = false;

    var serializedObject = JsonConvert.SerializeObject(
        new  username = "username", password = "password" 
        );

    var request = new HttpRequestMessage(HttpMethod.Post, "authenticate")
    
        Content = new StringContent(serializedObject, Encoding.UTF8, "application/json")
    ;

    var response = await client.SendAsync(request);

    response.EnsureSuccessStatusCode();

    var content = await response.Content.ReadAsStringAsync();

它将创建以下请求:

POST http://127.0.0.1:8888/v1/authenticate HTTP/1.1
cache-control: no-cache
Postman-Token: db8f2dd-cbf0-413c-ad5b-20af0543a31d
User-Agent: PostmanRuntime/7.6.0
Accept: */*
Content-Type: application/json; charset=utf-8
Host: 127.0.0.1:8888
Content-Length: 45
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

"username":"username","password":"password"

希望这会有所帮助。

【讨论】:

以上是关于使用 HttpClient 将 Content-Type 设置为“application/json”并将对象添加到正文的主要内容,如果未能解决你的问题,请参考以下文章

将 JwtSecurityToken 与 HttpClient 一起使用

使用 POST 方法将 HttpWebRequest 转换为 HttpClient

如何将 Ninject 与 HttpClient 一起使用

将 DelegatingHandler 与 HttpClient 上的自定义数据一起使用

是否可以将 HttpClient 配置为不保存 cookie?

使用 HttpClient,如何将 XDocument 直接保存到请求流中?