# HttpClient Http请求客户端连接池。 [TOC] 使用方式简单,步骤按照下面的来。 ## 添加连接池 首先我们打开AppServer,添加连接池的声明。 ```php public function initAsynPools() { parent::initAsynPools(); $this->addAsynPool('GetIPAddress',new HttpClientPool($this->config,'http://int.dpool.sina.com.cn')); $this->addAsynPool('WeiXinAPI',new HttpClientPool($this->config,'https://api.weixin.qq.com')); } ``` 我们通过继承initAsynPools的方法为我们的框架添加了2个http连接池。 HttpClientPool的构造函数中$config传框架的Config实例,$baseUrl请注意如果你要访问https://api.weixin.qq.com/1/2/34/5/6/abc 类似这样的网址,那么它的baseUrl为https://api.weixin.qq.com。 ## 使用方法 我们打开我们需要进行访问的代码,以下我们假设在controller中进行访问。 ```php /** * @var HttpClientPool */ protected $GetIPAddressHttpClient; public function initialization($controller_name, $method_name) { parent::initialization($controller_name, $method_name); $this->GetIPAddressHttpClient = get_instance()->getAsynPool('GetIPAddress'); } ``` 我们在initialization初始化函数中获得这个HttpClientPool。 >连接池可以在__construct和initialization中初始化,区别在于initialization每次访问都会执行,连接池只需要初始化一次即可,推荐在__construct进行初始化。 接下来我们就可以在代码中书写我们需要访问的api了。 ```php public function http_ip_test() { $ip = $this->http_input->server('remote_addr'); $response = $this->GetIPAddressHttpClient->httpClient ->setQuery(['format' => 'json', 'ip' => $ip]) ->coroutineExecute('/iplookup/iplookup.php'); } ``` ## 对象属性 * $body 请求响应后服务器端返回的内容 * $statusCode 服务器端返回的Http状态码,如404、200、500等 * $set_cookie_headers 服务器端返回的原始COOKIE信息,包括了domain 和path项 * $headers Http请求头 * $cookies Http Cookie ## 异常错误码 某些情况下服务器端没有正常返回数据,底层会将$statusCode标记为负数。 * -1:连接超时,服务器未监听端口或网络丢失,可以读取$errCode获取具体的网络错误码 * -2:请求超时,服务器未在规定的timeout时间内返回response * -3:客户端请求发出后,服务器强制切断连接