繁体   English   中英

如何在 .NET 中用 HttpClient 替换过时的 WebClient POST+ZIP 6

[英]How to replace obsolete WebClient POST+ZIP with HttpClient in .NET 6

由于 WebClient 在 .NET 6 中被弃用,使用 WebClient 将以下代码转换为使用 HttpClient 的等效代码的最佳解决方案是什么?

byte[] data = Converter(...); // object to zipped json string

var client = new WebClient();
client.Headers.Add("Accept", "application/json");
client.Headers.Add("Content-Type", "application/json; charset=utf-8");
client.Headers.Add("Content-Encoding", "gzip");
client.Encoding = Encoding.UTF8;

byte[] response = webClient.UploadData("...url...", "POST", data);
string body = Encoding.UTF8.GetString(response);

此代码有效,但只接受简单的 json 字符串作为输入:

var request = new HttpRequestMessage()
{
    RequestUri = new Uri("...url..."),
    Version = HttpVersion.Version20,
    Method = HttpMethod.Post,
    Content = new StringContent("...json string...", Encoding.UTF8, "application/json");
};

var client = new HttpClient();
var response = client.SendAsync(request).Result;

我需要一个解决方案来发布压缩的 json 字符串。

谢谢!

毫不奇怪,您成功地只发送了简单的字符串,因为您使用了字符串内容,它用于(鼓声!)字符串内容。

那么,如果您想以字节数组的形式发送二进制数据怎么办? 好吧,答案很简单:不要使用StringContent 相反,使用(鼓声加剧) ByteArrayContent

为了添加内容类型,您可以这样做:

var content = new StringContent(payload, Encoding.UTF8);
content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");

如果您想像使用 webclient 一样添加标头:

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

//OR 

var header = new KeyValuePair<string, string>(key: "Accept", value: "application/json");
client.DefaultRequestHeaders.Add(header.Key, header.Value));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM