使HTTP客户端同步:等待响应 [英] Make http client synchronous: wait for response

查看:98
本文介绍了使HTTP客户端同步:等待响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要上传一些文件,而某些文件失败,因为帖子是异步的而不是同步的。

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..

我要等待响应。

如何使该呼叫成为同步呼叫?

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

任何帮助表示赞赏!

推荐答案

更改

await content.ReadAsStringAsync().ConfigureAwait(false)

content.ReadAsStringAsync().Result

ReadAsStringAsync返回一个Task对象。该行末尾的 .Result告诉编译器返回内部字符串。

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

这篇关于使HTTP客户端同步:等待响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆