将 WebClient.UploadString() 替换为 HttpClient.PostAsync

Replace WebClient.UploadString() to HttpClient.PostAsync

我想在我的代码中将 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);

本页有指定的解决方案:

您可以决定是异步发布还是同步发布,例如:

HttpResponseMessage x = await httpClient.PostAsync(fullUrl, content);

你也可以替换

string payload = System.IO.File.ReadAllText("e:\IIF-Input3 (1).xml");
        try
        {
            System.Net.WebClient client = new System.Net.WebClient();
            client.Encoding = Encoding.UTF8;
            string res = client.UploadString("http://1.2.3.4:80/RunJson?name=Test", "POST", payload);
        }
        catch (System.Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

string payload = System.IO.File.ReadAllText("e:\IIF-Input3 (1).xml");
var content = new System.Net.Http.StringContent(payload, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded");
        var httpClient = new System.Net.Http.HttpClient();
        httpClient.BaseAddress = new Uri("http://1.2.3.4:80/");
        System.Net.Http.HttpResponseMessage response = httpClient.PostAsync("/RunJson?name=Test", content).Result;

        string result = response.Content.ReadAsStringAsync().Result;