简体   繁体   English

使http客户端同步:等待响应

[英]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! 任何帮助赞赏!

change 更改

await content.ReadAsStringAsync().ConfigureAwait(false)

to

content.ReadAsStringAsync().Result

the ReadAsStringAsync returns a Task object. ReadAsStringAsync返回一个Task对象。 the '.Result' in the end of the line tell the compiler to return the inner string. 该行末尾的'.Result'告诉编译器返回内部字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM