官方文档:https://guzzle-cn.readthedocs.io/zh_CN/latest/index.html
github: https://github.com/guzzle/guzzle

安装

composer require guzzlehttp/guzzle

自己封装了一个简单的类,用来get post

<?php
/**
 * Created by PhpStorm.
 * Date: 2019/4/7
 * Time: 12:01
 */
namespace App\Services;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class HttpService{

    protected $client;
    protected $error;

    public $url;
    public $request_data = [];
    public $quest_method = 'GET';

    public function __construct()
    {
        $this->client = new Client([
            'timeout'   =>  3.0
        ]);
    }

    //设置URL
    public function setUrl(string $url = ''){
        $this->url = $url;
        return $this;
    }
    //设置访问方法
    public function setMthod(string $method = ''){
        $this->quest_method = $method;
        return $this;
    }
    //设置请求变量
    public function setRequestData(array $request_data = []){
        $this->request_data = $request_data;
        return $this;
    }

    //获取get请求结果
    protected function _request(){
        switch ($this->quest_method){
            case 'GET':
                if ($this->request_data){
                    $this->url = $this->url .'?'. http_build_query($this->request_data);
                    $this->request_data = [];
                }
                break;
            default:
                break;
        }
        $res = [];
        try {
            $res = $this->client->request($this->quest_method,$this->url,$this->request_data);
        } catch (RequestException $e) {
            //echo $e->getRequest();
            if ($e->hasResponse()) {
//                $res = $e->getResponse();
                return false;
            }
        }
        return $res;
    }

    //返回结果
    public function getResult(){

        $response = $this->_request();
        if ($response && $response->getStatusCode() == '200'){
            $content = $response->getBody()->getContents();
            $res = is_null(json_encode($content)) ? $content : json_decode($content,true);
            return $res;
        } else{
            return false;
        }
    }

}

用法

<?php
use App\Service\HttpService;
$httpservice = new HttpService();
$param = [
    'appid'   =>   '1111',
    'page'    =>   '1'
];
$res = $httpservice->setUrl('url')
            ->setMthod('GET')->setRequestData($param)->getResult();
var_dump($res);

解决 laravel-admin between datetime 假如数据库是时间戳int类型无法筛选。

laravel-admin默认的between->datetime(),查询默认是datetime类型,但是假如数据库是时间戳类型就会报错,又不想改底层文件的话可以试试加自定义筛选功能...

阅读全文

php解析英文语句,自动分解。

参考:https://www.php.net/manual/en/function.str-split.php 最近碰到一个问题,客户的英文地址太长,超出接口api字段长度,所以需要解析下语句分解发送。 ...

阅读全文

记录一个laravel-excel导出表格值为0导出excel显示空的解决方法。

最近在使用laravel-excel导出表格的时候,发现假如字段值为0的情况下,导出的excel中直接显示为空,找到一个方法解决,如下. 在laravel-excel的config配置中...

阅读全文

欢迎留言