HttpClient wows !

I was helping a colleague doing sync stuff in a addin for a big app, and in order to recreate the problem, i decided to write some test code in a console app (which is not async).

That was relatively easy, and this is what the code looked like:

<p class="brush:csharp">var submitFileTask = system.SubmitFileAsync(new byte[] { 1, 2, 3 }, "asdf.pdf", "RequestedFile");</p>
<p class="brush:csharp">submitFileTask.Wait();</p>

That code went directly in the main method and it fixed my async in a console problem.

But that SubmitFileAsync method used HttpClient, and i had never used it. Wow, what simplicity !!!

A http get which returns json is simply a matter of these few lines:

uri = "https://something.com/getjson";
response = await httpClient.GetAsync(uri);
response.EnsureSuccessStatusCode();
var x = response.Content.ReadAsStringAsync().Result;

A http post which sends json stuff could look like this:

uri = "https://something.com/postjson";
var data= Newtonsoft.Json.JsonConvert.SerializeObject(new { MachineName = "test", Name = "Erik" });
response = await httpClient.PostAsync(uri, new StringContent(data, Encoding.UTF8, "application/json"));
response.EnsureSuccessStatusCode();

Then we had to send a file, and the api stated a multipart/form-data content type… So easy with this:

uri = "https://something.com/postMultiPartFormData";
MultipartFormDataContent formMultiPart = new MultipartFormDataContent("-----" + Guid.NewGuid());
formMultiPart.Add(new StringContent(Reason), "Reason");
formMultiPart.Add(new ByteArrayContent(fileContent), "File", fileName);
response = await httpClient.PostAsync(uri, formMultiPart);
response.EnsureSuccessStatusCode();

Now isn’t that simple !

 
Comments

No comments yet.