【问题标题】:HTTPClient Post Request with Headers and Body带有标头和正文的 HTTPClient 发布请求
【发布时间】:2019-05-26 17:12:50
【问题描述】:

我想使用 HttpClient 设置 Content-Type 和 Authorization Headers 并想为 body(request) 加载 xml 文件并发送 Post 请求。

我已经搜索了将标头和正文结合起来的 Post 请求。

使用 HttpRequestMessage 设置标头。

   HttpClient clientTest = new HttpClient();

   HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post,url);


   httpRequest.Content = new StringContent(string.Empty, Encoding.UTF8, "application/vnd.citrix.sessionparams+xml");
   httpRequest.Headers.Authorization = new AuthenticationHeaderValue("CitrixAuth", "H4sIAAAAAAAEAK1X2Y6jyBL9lZLnEbnZt1J");

设置 xml 正文 -

XDocument xml = XDocument.Load("RequestSession.xml");

转换为 Document.ToString()

var httpContent = new StringContent(xml.Document.ToString(), Encoding.UTF8, "application/vnd.citrix.sessionstate+xml");

请帮助我结合使用 HttpClient 的 Post Request 的标头和正文。

【问题讨论】:

  • 您只需发送HttpRequestMessage。我不明白你所说的“combine”是什么意思:var response = await clientTest.SendAsync(httpRequest);
  • Crowcoder - 感谢您的回复。我有帖子请求的标题和正文。您正在发送请求的标头 - httpRequest 对象。但我有一个身体 - Requessession.xml 我也需要为 PostAsync 发送这个。
  • 是的,它就是这样工作的。您设置标题。你设置身体。你发送请求。请更好地解释问题。
  • 它给了我“错误请求”作为响应,因为我忽略了要发送的正文。

标签: c# http web httpclient


【解决方案1】:

我不知道这是否是对您正在调用的服务的有效请求,但要设置标头和正文并发送请求,它将如下所示:

HttpClient clientTest = new HttpClient();

HttpRequestMessage httpRequest = new HttpRequestMessage(HttpMethod.Post,url);

httpRequest.Content = new StringContent(xml.Document.ToString(), Encoding.UTF8, "application/vnd.citrix.sessionstate+xml");
httpRequest.Headers.Authorization = new AuthenticationHeaderValue("CitrixAuth", "H4sIAAAAAAAEAK1X2Y6jyBL9lZLnEbnZt1J");

var response = await clientTest.SendAsync(httpRequest);

如果您收到 400 错误请求,那是因为您发送的 what 不适合 API,而不是因为您发送的 方式

【讨论】:

  • 谢谢。有效。我没有在 StringContent 类中发送正文内容。这就是我收到错误请求响应的原因。感谢您的解决方案。
猜你喜欢
  • 2019-06-23
  • 2017-08-31
  • 2020-12-23
  • 2019-12-18
  • 2018-03-28
  • 2021-08-13
  • 2018-12-06
  • 2022-01-23
  • 1970-01-01
相关资源
最近更新 更多