由于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字符串。
谢谢!
发布于 2022-04-12 09:40:06
不足为奇的是,您只发送了简单的字符串,因为您使用了StringContent,,它用于(鼓滚!)字符串内容。
那么,如果要以字节数组的形式发送二进制数据,怎么办?答案很简单:不要使用StringContent。相反,使用(鼓辊强化) 。
发布于 2022-04-16 07:51:30
为了添加内容类型,可以这样做:
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));
https://stackoverflow.com/questions/71839969
复制相似问题