我想在我的代码中将 WebClient 替换为 HttpClient。我必须在 HttpClient 中使用什么 HttpContent 来替换 WebClient.UploadString? 我的网络客户端代码:
string data = string.Format("name={0}&warehouse={1}&address={2}", name, shop.Warehouse.Id, shop.Address);
using (var wc = new WebClient()) {
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
wc.Encoding = Encoding.UTF8;
string fullUrl = BaseUrl + url;
string response = wc.UploadString(fullUrl, data);
// ...
}
请您参考如下方法:
您可以构建您的 postdata 并在 FormUrlEncodedContent 的实例中使用它,如下所示:
// This is the postdata
var data = new List<KeyValuePair<string, string>>();
data.Add(new KeyValuePair<string, string>("Name", "test"));
HttpContent content = new FormUrlEncodedContent(data);
此页面上指定了解决方案:
How to use System.Net.HttpClient to post a complex type?
您可以决定是异步发布还是同步发布,例如:
HttpResponseMessage x = await httpClient.PostAsync(fullUrl, content);
