Reputation: 1122
I want to replace WebClient to HttpClient in my code. What HttpContent I have to use in HttpClient to replace WebClient.UploadString? My WebClient code:
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);
// ...
}
Upvotes: 4
Views: 7656
Reputation: 168
you can also replace
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);
}
with
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;
Upvotes: 3
Reputation: 14889
You can construct your postdata and use it in the instance of the FormUrlEncodedContent like so:
// This is the postdata
var data = new List<KeyValuePair<string, string>>();
data.Add(new KeyValuePair<string, string>("Name", "test"));
HttpContent content = new FormUrlEncodedContent(data);
There are solutions specified on this page:
How to use System.Net.HttpClient to post a complex type?
You can decide on posting it asynchronously or synchronously for example:
HttpResponseMessage x = await httpClient.PostAsync(fullUrl, content);
Upvotes: 5