Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make http client synchronous: wait for response

I have some file to upload and some of the files failed because the post is asynchronous and not synchronous..

I'm trying to make this call as synchronized call..

I want to wait for the response.

How can I make this call as synchronous?

static async Task<JObect> Upload(string key, string url, string 
                                 sourceFile, string targetFormat)
{ 
    using (HttpClientHandler handler = new HttpClientHandler { 
                                           Credentials = new NetworkCredential(key, "") 
                                       })
    using (HttpClient client = new HttpClient(handler))
    {
         var request = new MultipartFormDataContent();
         request.Add(new StringContent(targetFormat), "target_format");
         request.Add(new StreamContent(File.OpenRead(sourceFile)),
                                       "source_file",
                                        new FileInfo(sourceFile).Name);

        using (HttpResponseMessage response = await client.PostAsync(url,
                                                           request).ConfigureAwait(false))

        using (HttpContent content = response.Content)
        {
            string data = await content.ReadAsStringAsync().ConfigureAwait(false);
            return JsonObject.Parse(data);
        }
    }
}

Any help appreciated!

like image 452
Alon Shmiel Avatar asked Jun 30 '15 04:06

Alon Shmiel


2 Answers

change

await content.ReadAsStringAsync().ConfigureAwait(false)

to

content.ReadAsStringAsync().Result

the ReadAsStringAsync returns a Task object. the '.Result' in the end of the line tell the compiler to return the inner string.

like image 174
michael berezin Avatar answered Oct 23 '22 06:10

michael berezin


That should do it:

static async Task<JObect> Upload(string key, string url, string 
                             sourceFile, string targetFormat)
{ 
    using (HttpClientHandler handler = new HttpClientHandler { 
                                           Credentials = new NetworkCredential(key, "") 
                                   })
    using (HttpClient client = new HttpClient(handler))
    {
         var request = new MultipartFormDataContent();
         request.Add(new StringContent(targetFormat), "target_format");
         request.Add(new StreamContent(File.OpenRead(sourceFile)),
                                   "source_file",
                                    new FileInfo(sourceFile).Name);

        using (HttpResponseMessage response = await client.PostAsync(url,request))

        using (HttpContent content = response.Content)
        {
            string data = await content.ReadAsStringAsync();
            return JsonObject.Parse(data);
        }
    }
}
like image 1
NCC-2909-M Avatar answered Oct 23 '22 05:10

NCC-2909-M