guzzlehttp/guzzle使用

本文介绍Guzzle,一个用于简化PHP中HTTP请求的库,演示了如何安装、使用及处理响应。通过实例展示了如何设置超时、错误处理和定制header。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 中文文档: https://guzzle-cn.readthedocs.io/zh_CN/latest/overview.html
  • GITHUB:https://github.com/guzzle/guzzle/

简介:Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.

安装: composer require guzzlehttp/guzzle

案例:

<?php

namespace App\Http\Controllers;

use GuzzleHttp\RequestOptions;

class TestController extends Controller
{
    protected $headers = [];

    public function __construct()
    {
        $this->headers = [
            'time' => time(),
        ];
    }

    public function index()
    {
        $uri = 'http://scrm.xcyc.com/api/test';

        $params['a'] = 1;
        $params['b'] = 2;

        $options = [
            RequestOptions::TIMEOUT => 3,
            RequestOptions::HTTP_ERRORS => false,
            RequestOptions::HEADERS => $this->headers,
            RequestOptions::QUERY => $params,
        ];

        $client = new \GuzzleHttp\Client();
        $res = $client->request('POST', $uri, $options);

        $contents = $res->getBody()->getContents();

        // 失败的情况
        if ($res->getStatusCode() != 200) {
            throw new \Exception(__('心诚直销网服务请求失败'), $res->getStatusCode());
        }

        return json_decode($contents, true);
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值