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

时间:2015-03-28 09:21:26

标签: c# post httpclient webclient

我想在我的代码中将WebClient替换为HttpClient。我必须在HttpClient中使用什么HttpContent来替换WebClient.UploadString? 我的WebClient代码:

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);
    // ...
}

2 个答案:

答案 0 :(得分:3)

您可以构建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);

答案 1 :(得分:0)

你也可以替换

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;