封装 PHP curl http 请求 (全) Composer 安装 httpbuilder,支持 GET,POST,PUT,DELETE

composer 安装:composer require ethansmart/httpbuilder
github 地址:https://github.com/roancsu/httpbuilder

在PHP 框架中可以使用 guzzlehttp 来构建HTTP Request 服务,但是guzzle 太重了,用起来比较繁琐,所以我用curl封装了PHP HTTP Request Client,支持 GET,POST,PUT,DELETE 方法,并且对文件上传有安全检测功能等等,使用也非常简单,效率高。

Usage:

构建 HttpClient

protected $client ;
function __construct()
{
    $this->client = HttpClientBuilder::create()->build();
}

GET Request

$data = [
    'uri'=>'https://www.baidu.com'
];

return $this->client
    ->setHeaders('Content-Type:application/json')
    ->setHeaders('X-HTTP-Method-Override:GET')
    ->setHeaders('Request_id: Ethan')
    ->setTimeout(10)
    ->Get($data);

POST Request


$data = [
    'uri'=>'https://www.baidu.com',
    'params'=> [
        'user'=>ethan
     ]
];

return $this->client
    ->setHeaders('Content-Type:application/json')
    ->Post($data);

PUT 、DELETE Request


$data = [
    'uri'=>'https://www.baidu.com',
    'params'=> [
        'user'=>ethan
     ]
];

return $this->client
    ->setHeaders('Content-Type:application/json')
    ->Put($data); // Delete($data)

扩展
文件上传

Http/Client.php
但post 数据 大于1k时,设置Expect ;

<?php

namespace App\Services\Tools\HttpClient\Http;

use Log;

/**
 * Class HttpClient
 * @package Ethansmart\HttpBuilder\Http
 * Support Http Method : GET, POST, PUT , DELETE
 */

class Client
{
    private $ch ;
    private $url ;
    private $method ;
    private $params ;
    private $timeout;
    protected $multipart ;

    public function __construct()
    {
        $this->timeout = 120 ;
    }

    public function Get($data)
    {
        $data['method'] = "GET";
        return $this->performRequest($data);
    }

    public function Post($data)
    {
        $data['method'] = "POST";
        return $this->performRequest($data);
    }

    public function Put($data)
    {
        $data['method'] = "PUT";
        return $this->performRequest($data);
    }

    public function Delete($data)
    {
        $data['method'] = "DELETE";
        return $this->performRequest($data);
    }

    public function Upload($data)
    {
        $data['method'] = "POST";
        $this->multipart = true;
        return $this->performRequest($data);
    }

    /**
     * Http 请求
     * @param $data
     * @return array
     */
    public function performRequest($data)
    {
        $this->ch = curl_init();
        $url = $data['url'];
        try {
            $this->dataValication($data);
        } catch (\Exception $e) {
            return ['code'=>-1, 'msg'=>$e->getMessage()];
        }

        $timeout = isset($data['timeout'])?$data['timeout']:$this->timeout;
        $headers = $this->setHeaders($data);
        curl_setopt($this->ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($this->ch, CURLOPT_HEADER, true);
        curl_setopt($this->ch, CURLINFO_HEADER_OUT, true);
        if (!empty($headers)) {
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($this->ch, CURLOPT_NOBODY, false);
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, $this->timeout);
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $this->method); //设置请求方式

        if ($this->method=="GET") {
            if(strpos($this->url,'?')){
                $this->url .= http_build_query($this->params);
            }else{
                $this->url .= '?' . http_build_query($this->params);
            }
        }else{
            curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->multipart?$this->params:http_build_query($this->params));
        }

        curl_setopt($this->ch, CURLOPT_URL, $this->url);

        if (1 == strpos('$'.$this->url, "https://")) {
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        $result = curl_exec($this->ch);

//        if (curl_getinfo($this->ch, CURLINFO_HTTP_CODE) == '200') {}

        if(!curl_errno($this->ch)){
            list($response_header, $response_body) = explode("\r\n\r\n", $result, 2);
            Log::info("Request Headers: ". json_encode($response_header));
            Log::info("Request Body :".json_encode($response_body));
            $contentType = curl_getinfo($this->ch, CURLINFO_CONTENT_TYPE);

            $info = curl_getinfo($this->ch);
            Log::info('耗时 ' . $info['total_time'] . ' Seconds 发送请求到 ' . $info['url']);
            $response = ['code'=>0, 'msg'=>'OK', 'data'=>$response_body, 'contentType'=>$contentType];
        }else{
            Log::info('Curl error: ' . curl_error($this->ch)) ;
            $response = ['data'=>(object)['code'=>-1, 'msg'=>"请求 $url 出错: Curl error: ". curl_error($this->ch)]];
        }

        curl_close($this->ch);

        return $response;
    }

    /**
     * 设置Header信息
     * @param $data
     * @return array
     */
    public function setHeaders($data)
    {
        $headers = array();
        if (isset($data['headers'])) {
            foreach ($data['headers'] as $key=>$item) {
                $headers[] = "$key:$item";
            }
        }
        $headers[] = "Expect:"; // post数据大于1k时,默认不需要添加Expect:100-continue

        return $headers;
    }

    public function setTimeout($timeout)
    {
        if (!empty($timeout) || $timeout != 30) {
            $this->timeout = $timeout ;
        }

        return $this;
    }

    /**
     * 数据验证
     * @param $data
     * @throws \Exception
     */
    public function dataValication($data)
    {
        if(!isset($data['url']) || empty($data['url'])){
            throw new \Exception("HttpClient Error: Uri不能为空", 4422);
        }else{
            $this->url = $data['url'];
        }

        if(!isset($data['params']) || empty($data['params'])){
            $this->params = [];
        }else{
            $this->params = $data['params'];
        }

        if(!isset($data['method']) || empty($data['method'])){
            $this->method = "POST";
        }else{
            $this->method = $data['method'];
        }
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
Ethan Smart & AI Algorithm
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2

能问下我引入的时候报

file

请问下是怎么回事

6年前 评论

@ChaosKevin 这是包路径没有找到, 你更新一下资源包

6年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!