为什么要使用的HttpClient的同步连接 [英] Why use HttpClient for Synchronous Connection

查看:155
本文介绍了为什么要使用的HttpClient的同步连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立一个类库与API进行交互。我需要调用API和处理XML响应。我可以看到使用的HttpClient异步连接的好处,但我在做什么纯粹是同步的,所以看不到了HttWebRequests任何显著的好处。

如果任何人都可以摆脱任何光线,我将不胜AP preciate它。我不是一个使用新技术的缘故吧。


解决方案

  

但我在做什么完全是同步的。


您可以使用的HttpClient 同步请求就好了:

 使用(VAR的客户=新的HttpClient())
{
    VAR响应= client.GetAsync(http://google.com)。结果;    如果(response.IsSuccessStatus code)
    {
        //调用。结果你执行的是同步调用
        VAR responseContent = response.Content;        //调用。结果你被同步读取结果
        字符串responseString = responseContent.ReadAsStringAsync()结果。        Console.WriteLine(responseString);
    }
}

至于为什么要使用的HttpClient在WebRequest的来讲,好了,HttpClient的是块新的孩子,可能包含在旧的客户端的改进。

I am building a class library to interact with an API. I need to call the API and process the XML response. I can see the benefits of using HttpClient for Asynchronous connectivity, but what I am doing is purely synchronous, so cannot see any significant benefit over HttWebRequests.

If anyone can shed any light I would greatly appreciate it. I am not one for using new technology for the sake of it.

解决方案

but what i am doing is purely synchronous

You could use HttpClient for synchronous requests just fine:

using (var client = new HttpClient())
{
    var response = client.GetAsync("http://google.com").Result;

    if (response.IsSuccessStatusCode)
    {
        // by calling .Result you are performing a synchronous call
        var responseContent = response.Content; 

        // by calling .Result you are synchronously reading the result
        string responseString = responseContent.ReadAsStringAsync().Result;

        Console.WriteLine(responseString);
    }
}

As far as why you should use HttpClient over WebRequest is concerned, well, HttpClient is the new kid on the block and could contain improvements over the old client.

这篇关于为什么要使用的HttpClient的同步连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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