HttpClient 请求的自定义标头

编程入门 行业动态 更新时间:2024-10-24 10:25:15
本文介绍了HttpClient 请求的自定义标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何向 HttpClient 请求添加自定义标头?我正在使用 PostAsJsonAsync 方法发布 JSON.我需要添加的自定义标题是

How do I add a custom header to a HttpClient request? I am using PostAsJsonAsync method to post the JSON. The custom header that I would need to be added is

"X-Version: 1"

这是我到目前为止所做的:

This is what I have done so far:

using (var client = new HttpClient()) { client.BaseAddress = new Uri("api.clickatell/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "xxxxxxxxxxxxxxxxxxxx"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = client.PostAsJsonAsync("rest/message", svm).Result; }

推荐答案

var request = new HttpRequestMessage { RequestUri = new Uri("[your request url string]"), Method = HttpMethod.Post, Headers = { { "X-Version", "1" } // HERE IS HOW TO ADD HEADERS, { HttpRequestHeader.Authorization.ToString(), "[your authorization token]" }, { HttpRequestHeader.ContentType.ToString(), "multipart/mixed" },//use this content type if you want to send more than one content type }, Content = new MultipartContent { // Just example of request sending multipart request new ObjectContent<[YOUR JSON OBJECT TYPE]>( new [YOUR JSON OBJECT TYPE INSTANCE](...){...}, new JsonMediaTypeFormatter(), "application/json"), // this will add 'Content-Type' header for the first part of request new ByteArrayContent([BINARY DATA]) { Headers = { // this will add headers for the second part of request { "Content-Type", "application/Executable" }, { "Content-Disposition", "form-data; filename="test.pdf"" }, }, }, }, };

更多推荐

HttpClient 请求的自定义标头

本文发布于:2023-11-26 21:27:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635250.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!