UWP技术问询:如何在GET请求中添加Content-Type头且不含Content-Length
这个问题确实挺棘手的——第三方API要求GET请求带Content-Type,但又完全排斥Content-Length头,哪怕值是0都不行。我之前对接过类似的奇葩接口,给你分享个靠谱的解决思路:自定义一个不自动添加Content-Length的HttpContent实现。
具体实现方案
- 首先创建一个继承自
HttpContent的自定义类,我们叫它EmptyContentTypeContent,在这个类里可以完全控制请求头的添加逻辑,避免自动生成Content-Length:
public class EmptyContentTypeContent : HttpContent { private readonly string _contentType; public EmptyContentTypeContent(string contentType) { _contentType = contentType; Headers.ContentType = new MediaTypeHeaderValue(contentType); } protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { // 不需要发送任何内容,直接返回完成的任务 return Task.CompletedTask; } protected override bool TryComputeLength(out long length) { // 返回false表示不计算内容长度,HttpClient就不会自动添加Content-Length头 length = 0; return false; } }
- 然后在发送GET请求时,用这个自定义类代替
HttpStringContent:
using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Get, "https://第三方API地址"); // 传入你需要的Content-Type值,比如"application/json" request.Content = new EmptyContentTypeContent("application/json"); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); // 处理响应内容 }
为什么这个方案可行?
- 默认的
HttpStringContent(包括其他内置HttpContent实现)会在TryComputeLength里返回true并提供长度,导致HttpClient自动添加Content-Length头; - 我们自定义的类通过
TryComputeLength返回false,告诉HttpClient不要自动处理内容长度,同时手动设置了Content-Type头,完美满足第三方API的要求。
内容的提问来源于stack exchange,提问作者JM8s
相关产品推荐
相关产品推荐

