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



由于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字符串的解决方案。

谢谢!

毫不奇怪,您只发送了简单的字符串,因为您使用了String内容,这意味着(鼓轮!(String的内容。

那么,如果您想以字节数组的形式发送二进制数据,该怎么办呢?答案很简单:不要使用StringContent。相反,请使用(鼓声增强(ByteArrayContent

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

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

如果你想像使用web客户端那样添加标题:

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));

相关内容

最新更新