<?php
/**
 * HTTP请求类
 */


class HttpTool {
    protected $connect_timeout;
    protected $request_timeout;

    public function __construct($connect_timeout = 5, $request_timeout = 55) {
        $this->connect_timeout = $connect_timeout;
        $this->request_timeout = $request_timeout;
    }

    public function httpRequest($url, $data, $type = 'POST', $header = [], $opt = [], &$curl_info = []) {
        $ch = curl_init($url);
        $options = array(
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_CONNECTTIMEOUT => $this->connect_timeout,
            CURLOPT_TIMEOUT => $this->request_timeout,
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_DNS_CACHE_TIMEOUT => 86400,
        );
        switch ($type) {
            case 'POST':
                $options[CURLOPT_POST] = 1;
                $options[CURLOPT_POSTFIELDS] = is_array($data) ? http_build_query($data) : $data;
                break;
            case 'GET':
                $options[CURLOPT_HTTPGET] = 1;
                empty($data) or $options[CURLOPT_URL] = $url . '?' . http_build_query($data);
                break;
        }
        $options = $opt + $options; // 数组联合运算
        curl_setopt_array($ch, $options);
        $response = curl_exec($ch);

        $curl_info = curl_getinfo($ch);
        if ($no = curl_errno($ch)) {
            $error = curl_error($ch);
            curl_close($ch);
            if(in_array(intval($no), [7, 28], true)) {
                throw new \DomainException("连接或请求{$url}超时:{$error}", $no);
            }
            throw new \DomainException("请求{$url}失败:" . $error, $no);
        }
        curl_close($ch);

        return $response;
    }

    public function soapRequest($url, $function_name, array $arguments, $opt = [], &$request_xml = '', &$response_xml = '') {
        try {
            ini_set('default_socket_timeout', $this->request_timeout);
            $options = array_merge([
                'cache_wsdl' => WSDL_CACHE_MEMORY,
                'connection_timeout' => $this->connect_timeout,
                'trace' => 1,
            ], $opt);
            libxml_disable_entity_loader(false);
            $client = new \SoapClient($url, $options);

            $response = $client->__soapCall($function_name, $arguments);

            $request_xml = $client->__getLastRequest();
            $response_xml = $client->__getLastResponse();

            return $response;
        } catch (\SoapFault $e) {
            //超时、连接不上
            if (in_array($e->faultcode, [
                'HTTP',
                'WSDL',
            ], true)) {
                throw new \DomainException("连接或请求{$url}超时", $e->getCode());
            }

            throw new \DomainException($e, $e->getCode());
        }
    }
}

小刘
220 声望4 粉丝