HTTP 客户端

未匹配的标注

HTTP 客户端

Yii2 框架的官方扩展 yii2-httpclient 为我们提供了 HTTP 客户端相关功能。

安装

安装此扩展的首选方式是通过 composer,命令如下:

composer require yiisoft/yii2-httpclient

或者在您的 composer.json 文件中的 require 部分增加以下内容:

"yiisoft/yii2-httpclient": "~2.0.0"

然后执行 composer install 命令即可。

基本用法

为了发送 HTTP 请求,你需要实例化 \yii\httpclient\Client 并使用它的 createRequest() 方法来创建一个新的 HTTP 请求。然后您应该根据您的目标,配置所有的请求参数并发送请求。最后,你会得到一个 yiii\httpclient\Response 实例,它保存了所有的响应信息和数据。例如:

use yii\httpclient\Client;

$client = new Client();
$response = $client->createRequest()
    ->setMethod('POST')
    ->setUrl('http://example.com/api/1.0/users')
    ->setData(['name' => 'John Doe', 'email' => 'johndoe@example.com'])
    ->send();
if ($response->isOk) {
    $newUserId = $response->data['id'];
}

你可以使用 get()post()put() 等快捷方法来简化新请求的准备工作。如果你使用单一的 yii\httpclient\Client 实例对同一个域进行多个请求(例如使用 REST API 的情况),你可以使用这个域设置它的 baseUrl 属性。这将允许您在创建新请求时只指定相对 URL。因此,对某些 REST API 的请求,可能如下所示:

use yii\httpclient\Client;

$client = new Client(['baseUrl' => 'http://example.com/api/1.0']);

$newUserResponse = $client->post('users', ['name' => 'John Doe', 'email' => 'johndoe@example.com'])->send();
$articleResponse = $client->get('articles', ['name' => 'Yii 2.0'])->send();
$client->post('subscriptions', ['user_id' => $newUserResponse->data['id'], 'article_id' => $articleResponse->data['id']])->send();

使用不同的内容格式

默认情况下,HTTP 请求数据以 form-urlencoded 的方式发送,例如 param1=value1&param2=value2。这是 web 表单的一种常见格式,但不是针对 REST API,后者通常要求内容应该是 JSON 或 XML 格式。你可以使用 format 属性或 setFormat() 方法,来设置请求内容使用的格式。主要支持以下格式:

  • \yii\httpclient\Client::FORMAT_JSON - JSON 格式
  • \yii\httpclient\Client::FORMAT_URLENCODED - urlencoded(RFC1738 查询字符串)
  • \yii\httpclient\Client::FORMAT_RAW_URLENCODED - urlencoded(PHP_QUERY_RFC3986 查询字符串)
  • \yii\httpclient\Client::FORMAT_XML - XML 格式

例如:

use yii\httpclient\Client;

$client = new Client(['baseUrl' => 'http://example.com/api/1.0']);
$response = $client->createRequest()
    ->setFormat(Client::FORMAT_JSON)
    ->setUrl('articles/search')
    ->setData([
        'query_string' => 'Yii',
        'filter' => [
            'date' => ['>' => '2015-08-01']
        ],
    ])
    ->send();

响应对象根据 Content-Type 头和内容本身,来自动检测内容格式。所以,在大多数情况下,你不需要为响应指定格式,你可以简单地使用 getData() 方法或 data 属性来解析它。继续上面的例子,我们可以通过以下方式得到响应数据:

$responseData = $response->getData(); // get all articles
count($response->data) // count articles
$article = $response->data[0] // get first article

使用原始内容

内置的格式,并非是要强制性使用的。您可以为 HTTP 请求指定原始内容,同样也可以处理响应的原始内容。例如:

use yii\httpclient\Client;

$client = new Client(['baseUrl' => 'http://example.com/api/1.0']);
$response = $client->createRequest()
    ->setUrl('articles/search')
    ->addHeaders(['content-type' => 'application/json'])
    ->setContent('{query_string: "Yii"}')
    ->send();

echo 'Search results:<br>';
echo $response->content;

\yii\httpclient\Request 格式仅在 content 未设置时指定 data\yii\httpclient\Response 仅在 data 被请求时,解析 content

预配置请求与响应对象

如果你使用 \yiii\httpclient\Client 的单个实例来处理一些类似的请求,例如,在使用 REST API时,你可以简化并加快声明自己的请求和响应对象配置的代码开发速度。这可以通过 \yii\httpclient\ClientrequestConfigresponseConfig 字段来完成。你可能想设置 JSON 格式的所有由特定的客户端创建的请求,示例如下:

use yii\httpclient\Client;

$client = new Client([
    'baseUrl' => 'http://example.com/api/1.0',
    'requestConfig' => [
        'format' => Client::FORMAT_JSON
    ],
    'responseConfig' => [
        'format' => Client::FORMAT_JSON
    ],
]);

$request = $client->createRequest();
echo $request->format; // outputs: 'json'

Tip:您甚至可以在配置数组中使用 ‘class’ 键,为请求和响应对象指定你自己的类,来促进你需要的一些额外的功能。

使用请求头

您可以使用 setHeaders()addHeaders() 方法来指定请求头。你也可以使用 getHeaders() 方法 or headers 属性来获取已经定义的作为 \yii\web\HeaderCollection 实例的头。例如:

use yii\httpclient\Client;

$client = new Client(['baseUrl' => 'http://example.com/api/1.0']);
$request = $client->createRequest()
    ->setHeaders(['content-type' => 'application/json'])
    ->addHeaders(['user-agent' => 'My User Agent']);

$request->getHeaders()->add('accept-language', 'en-US;en');
$request->headers->set('user-agent', 'User agent override');

一旦你有了一个响应对象,你可以使用 getHeaders() 方法或 headers 属性来访问所有的响应头,例如:

$response = $request->send();
echo $response->getHeaders()->get('content-type');
echo $response->headers->get('content-encoding');

HTTP 基本认证

本客户端没有内置对 HTTP 身份验证的支持。如果你想使用 HTTP 基本认证,你需要添加一个符合 HTTP 基本验证格式 的合适头信息。你可以添加一个 Authorization 头,它包含单词 Basic,后跟一个空格和 base64 编码的字符串 username:password,示例如下:

$username = 'yii';
$password = 'verysecret';
$request->headers->set('Authorization', 'Basic ' . base64_encode("$username:$password"));

注意:HTTP 基本认证在明文中发送账号和密码,因此,它应该只在使用 HTTPS 的安全连接上使用。

使用 cookies

虽然 Cookies 是像报头值一样传输的,\yii\httpclient\Request\yii\httpclient\Request 仍然提供了单独的接口来使用 \yii\web\Cookie\yii\web\CookieCollection

你可以使用 setCookies()addCookies() 方法来指定请求的 cookie。你可以使用 getCookies() 方法或 cookies 属性来获取已经定义的 cookie ,并作为 yiii \web\CookieCollection 类的实例。示例如下:

use yii\httpclient\Client;
use yii\web\Cookie;

$client = new Client(['baseUrl' => 'http://example.com/api/1.0']);
$request = $client->createRequest()
    ->setCookies([
        ['name' => 'country', 'value' => 'USA'],
        new Cookie(['name' => 'language', 'value' => 'en-US']),
    ])
    ->addCookies([
        ['name' => 'view_mode', 'value' => 'full']
    ]);

$request->cookies->add(['name' => 'display-notification', 'value' => '0']);

一旦当你有了一个响应对象,你可以使用 getCookies() 方法或 cookies 属性访问所有的响应的 cookie,示例如下:

$response = $request->send();
echo $response->getCookies()->get('country');
echo $response->headers->get('PHPSESSID');

您可以使用简单的复制,将 cookie 从响应对象转移到请求。例如,假设我们需要在一些 web 应用程序中编辑用户配置文件,它只有在登录后才可用,所以,我们需要首先登录并使用创建的会话进行进一步的活动,代码如下:

use yii\httpclient\Client;

$client = new Client(['baseUrl' => 'http://example.com']);

$loginResponse = $client->post('login', [
    'username' => 'johndoe',
    'password' => 'somepassword',
])->send();

// $loginResponse->cookies->get('PHPSESSID') - holds the new session ID

$client->post('account/profile', ['birthDate' => '10/11/1982'])
    ->setCookies($loginResponse->cookies) // transfer response cookies to request
    ->send();

使用 Curl 下载文件

您可以下载一个文件,而无需将其全部内容加载到内存中(这一点,对于大文件特别有用)。使用 setOutputFile() 方法将流资源(例如使用 fopen())传递给请求对象。它将被传递到 CURLOPT_FILE cURL选项。

use yii\httpclient\Client;

$fh = fopen('/path/to/local/file', 'w');
$client = new Client([
    'transport' => 'yii\httpclient\CurlTransport'
]);
$response = $client->createRequest()
    ->setMethod('GET')
    ->setUrl('http://example.com/path/to/remote/file')
    ->setOutputFile($fh)
    ->send();

使用 Curl 上传文件

你可以使用 CURLFile (PHP >= 5.5.0)上传一个文件,而不需要将其全部内容加载到内存中(这一点,对于大文件特别有用)。

use yii\httpclient\Client;

$client = new Client([
    'transport' => 'yii\httpclient\CurlTransport',
]);
$response = $client->createRequest()
    ->setFormat(Client::FORMAT_CURL)
    ->setMethod('POST')
    ->setUrl('http://example.com')
    ->setData([
        'name' => 'John Doe',
        'email' => 'johndoe@example.com',
        'file1' => new \CURLFile('/path/to/file1'), 'text/plain', 'file1'),
        'file2' => new \CURLFile('/path/to/file2'), 'text/plain', 'file2'),
    ])
    ->send();

数据格式

数据格式决定了组成或解析 HTTP 消息内容的方式,例如,它决定了 \yii\httpclient\Message::$data 应该如何转换为 \yii\httpclient\Message::$content,反之亦然。默认支持以下格式:

  • \yii\httpclient\Client::FORMAT_JSON - JSON 格式
  • \yii\httpclient\Client::FORMAT_URLENCODED - urlencoded(RFC1738 查询字符串)
  • \yii\httpclient\Client::FORMAT_RAW_URLENCODED - urlencoded(PHP_QUERY_RFC3986 查询字符串)
  • \yii\httpclient\Client::FORMAT_XML - XML 格式

每种格式都有两个实体:formatter(格式器)parser(解析器)。前者决定由数据组成请求内容的方式,后者决定如何将原始响应内容解析为数据。

\yii\httpclient\Client 自动为上述所有格式选择相应的格式器和解析器。但是你可以使用 \yii\httpclient\Client::$formatters\yii\httpclient\Client::$parser 来改变这个行为。使用这些字段,您可以添加自己的格式或更改标准格式。例如:

use yii\httpclient\Client;

$client = new Client([
    'formatters' => [
        'myformat' => 'app\components\http\MyFormatter', // add new formatter
        Client::FORMAT_XML => 'app\components\http\MyXMLFormatter', // override default XML formatter
    ],
    'parsers' => [
        // configure options of the JsonParser, parse JSON as objects
        Client::FORMAT_JSON => [
            'class' => 'yii\httpclient\JsonParser',
            'asArray' => false,
        ]
    ],
]);

在创建你自己的解析器时,你应该实现 \yii\httpclient\ParserInterface,同时,创建格式化器需要实现 \yii\httpclient\FormatterInterface。例如:

use yii\httpclient\FormatterInterface;
use yii\httpclient\ParserInterface;
use yii\httpclient\Response;

class ParserIni implements ParserInterface
{
    public function parse(Response $response)
    {
        return parse_ini_string($response->content);
    }
}

class FormatterIni implements FormatterInterface
{
    public function format(Request $request)
    {
        $request->getHeaders()->set('Content-Type', 'text/ini; charset=UTF-8');

        $pairs = [];
        foreach ($request->data as $name => $value) {
            $pairs[] = "$name=$value";
        }

        $request->setContent(implode("\n", $pairs));
        return $request;
    }
}

传输

\yii\httpclient\Client 提供了几种不同的方式来实际发送 HTTP 消息,即几种预定义传输方式。具体如下:

  • \yii\httpclient\StreamTransport:使用 Streams 发送 HTTP 消息。默认情况下使用此传输,它不需要安装任何额外的 PHP 扩展或库,但不支持像批量发送这样的高级特性。
  • \yii\httpclient\CurlTransport:使用 cURL(Client URL 库) 发送 HTTP 消息。这种传输需要安装 PHP ‘curl’ 扩展,但提供了对高级功能的支持,如批量发送。
  • \yii\httpclient\MockTransport:主要在测试自动化环境中使用。它不发送任何真正的请求,而是返回指示它返回的响应。

您可以使用 \yii\httpclient\Client::$transport 属性将传输配置为特定的客户端,示例如下:

use yii\httpclient\Client;

$client = new Client([
    'transport' => 'yii\httpclient\CurlTransport'
]);

自定义传输

您可以创建自己的传输,它将以自己的方式执行消息发送。要做到这一点,你应该继承 yiii \httpclient\Transport 类,并至少实现 send() 方法。所有你需要做的就是确定 HTTP 响应内容和报头,然后你可以用 yii\httpclient\Client::createResponse(),为它们组成一个响应对象。示例如下:

use yii\httpclient\Transport;

class MyTransport extends Transport
{
    /**
     * @inheritdoc
     */
    public function send($request)
    {
        $responseContent = '???';
        $responseHeaders = ['???'];

        return $request->client->createResponse($responseContent, $responseHeaders);
    }
}

如果有一个方式发送多个请求具有更好的性能,例如,异步地并行发送它们,你也可以重写 batchSend() 方法。

请求选项

你可以使用 \yii\httpclient\Request::$options 来调整特定请求的执行。我们主要支持以下选项,但区分大小写:

  • timeout:integer,允许执行请求的最大秒数。
  • proxy:string,指定代理服务器地址的 URI(例如:tcp://proxy.example.com:5100)。
  • userAgent:string,在 HTTP 请求中使用的 User-Agent: 头的内容。
  • followLocation:boolean,是否遵循服务器作为 HTTP 报头的一部分发送的任何 Location: 报头。
  • maxRedirects:integer,要跟随的最大重定向数。
  • sslVerifyPeer:boolean,是否验证对端证书。
  • sslCafile:string,证书颁发机构文件在本地文件系统上的位置,应该与 ‘sslVerifyPeer’选项一起使用,以验证远程对等体的身份。
  • sslCapath:string,存放多个CA证书的目录。
  • sslLocalCert:文件系统上本地证书文件的路径。它必须是一个 PEM 编码的文件,包含您的证书和私钥。它可以选择性地包含颁发者的证书链。私钥也可以包含在由 sslLocalPk 指定的单独文件中。
  • sslLocalPk:在证书(sslLocalCert)和私钥文件是单独的文件的情况下的文件系统上本地私钥文件的路径。
  • sslPassphrase:用于对 sslLocalCert 文件进行编码的密码短语。

例如:

use yii\httpclient\Client;

$client = new Client();

$response = $client->createRequest()
    ->setMethod('POST')
    ->setUrl('http://domain.com/api/1.0/users')
    ->setData(['name' => 'John Doe', 'email' => 'johndoe@domain.com'])
    ->setOptions([
        'proxy' => 'tcp://proxy.example.com:5100', // use a Proxy
        'timeout' => 5, // set timeout to 5 seconds for the case server is not responding
    ])
    ->send();

Tip:你可以通过 yii\httpclient\Client::$requestConfig 设置默认的请求选项。如果你这样做了,使用 yii\httpclient\Request::addOptions() 来保留它们的值,如果你希望为请求添加额外的特定选项。

您也可以传递选项,这些选项对于特定的请求传输是特定的。通常在使用 yiii \httpclient\CurlTransport 的情况下会出现这种情况。例如:您可能希望为连接和接收数据指定分离的超时,PHP cURL 库支持这种超时。你可以这样做:

use yii\httpclient\Client;

$client = new Client([
    'transport' => 'yii\httpclient\CurlTransport' // only cURL supports the options we need
]);

$response = $client->createRequest()
    ->setMethod('POST')
    ->setUrl('http://domain.com/api/1.0/users')
    ->setData(['name' => 'John Doe', 'email' => 'johndoe@domain.com'])
    ->setOptions([
        CURLOPT_CONNECTTIMEOUT => 5, // connection timeout
        CURLOPT_TIMEOUT => 10, // data receiving timeout
    ])
    ->send();

有关特定选项支持的详细信息,请参阅特定的传输类文档。

Multi-part 内容(multipart/form-data)

HTTP 消息内容可能由不同内容类型的几个部分组成。这在文件上传请求的情况下通常是必要的。你可以使用 yii\httpclient\RequestaddContent()addFile()addFileContent() 方法来组合多部分内容。例如,如果您希望通过 web 表单模拟文件上传,您可以使用如下代码:

use yii\httpclient\Client;

$client = new Client();
$response = $client->createRequest()
    ->setMethod('POST')
    ->setUrl('http://domain.com/file/upload')
    ->addFile('file', '/path/to/source/file.jpg')
    ->send();

如果有 \yii\httpclient\Request::$data 指定,它的值将自动作为内容部分发送,以防请求被标记为多部分之一。例如,假设我们希望模拟表单的提交,具体如下:

<form name="profile-form" method="post" action="http://domain.com/user/profile" enctype="multipart/form-data">
    <input type="text" name="username" value="">
    <input type="text" name="email" value="">
    <input type="file" name="avatar">
    <!-- ... -->
</form>

你可以使用下面的代码来做到这一点:

use yii\httpclient\Client;

$client = new Client();
$response = $client->createRequest()
    ->setMethod('POST')
    ->setUrl('http://domain.com/user/profile')
    ->setData([
        'username' => 'johndoe',
        'email' => 'johndoe@domain.com',
    ])
    ->addFile('avatar', '/path/to/source/image.jpg')
    ->send();

请注意,附加多个具有相同名称的文件将导致它们被最新的文件覆盖。您必须自己控制附加文件的可能的表格输入索引。示例如下:

use yii\httpclient\Client;

$client = new Client();
$response = $client->createRequest()
    ->setMethod('POST')
    ->setUrl('http://domain.com/gallery')
    ->addFile('avatar[0]', '/path/to/source/image1.jpg')
    ->addFile('avatar[1]', '/path/to/source/image2.jpg')
    ...
    ->send();

批处理请求发送

HTTP 客户端允许你使用 \yii\httpclient\Client::batchSend() 方法,一次发送多个请求,代码如下:

use yii\httpclient\Client;

$client = new Client();

$requests = [
    $client->get('http://domain.com/keep-alive'),
    $client->post('http://domain.com/notify', ['userId' => 12]),
];
$responses = $client->batchSend($requests);

特定的传输可以从这种方法的使用中受益,从而提高性能。在内置的传输中,只有yii\httpclient\CurlTransport 这样做。它允许并行发送请求,这节省了程序执行时间。

Note:只有一些特殊的传输允许以特殊的方式处理 batchSend() 上的请求,这提供了一些好处。默认情况下,传输只是一个接一个地发送它们,而不会抛出任何错误或警告。如果希望实现性能提升,请确保为客户机配置了正确的传输。

batchSend() 方法返回响应数组,这些键对应于请求数组中的键。这允许你以简单的方式处理特定的请求响应,示例如下:

use yii\httpclient\Client;

$client = new Client();

$requests = [
    'news' => $client->get('http://domain.com/news'),
    'friends' => $client->get('http://domain.com/user/friends', ['userId' => 12]),
    'newComment' => $client->post('http://domain.com/user/comments', ['userId' => 12, 'content' => 'New comment']),
];
$responses = $client->batchSend($requests);

// result of `GET http://domain.com/news` :
if ($responses['news']->isOk) {
    echo $responses['news']->content;
}

// result of `GET http://domain.com/user/friends` :
if ($responses['friends']->isOk) {
    echo $responses['friends']->content;
}

// result of `POST http://domain.com/user/comments` :
if ($responses['newComment']->isOk) {
    echo "Comment has been added successfully";
}

事件

\yii\httpclient\Request 提供了几个事件,可以通过事件处理程序或行为来处理:

  • \yii\httpclient\Request::EVENT_BEFORE_SEND:在发送请求之前被引发
  • \yii\httpclient\Request::EVENT_AFTER_SEND:发送请求后引发

这些事件可以用来调整请求参数或接收到的响应。例如:

use yii\httpclient\Client;
use yii\httpclient\Request;
use yii\httpclient\RequestEvent;

$client = new Client();

$request = $client->createRequest()
    ->setMethod('GET')
    ->setUrl('http://api.domain.com')
    ->setData(['param' => 'value']);

// Ensure signature generation based on final data set:
$request->on(Request::EVENT_BEFORE_SEND, function (RequestEvent $event) {
    $data = $event->request->getData();

    $signature = md5(http_build_query($data));
    $data['signature'] = $signature;

    $event->request->setData($data);
});

// Normalize response data:
$request->on(Request::EVENT_AFTER_SEND, function (RequestEvent $event) {
    $data = $event->response->getData();

    $data['content'] = base64_decode($data['encoded_content']);

    $event->response->setData($data);
});

$response = $request->send();

将事件处理程序附加到 yiii \httpclient\Request 实例是不太实际的。你可以使用 \yii\httpclient\Client 类的事件来处理相同的用例,例如:

  • \yii\httpclient\Client::EVENT_BEFORE_SEND:在发送请求之前被引发
  • \yii\httpclient\Client::EVENT_AFTER_SEND:发送请求后引发

这些事件会在所有通过客户端创建的请求中以相同的方式被触发,并且具有与 \yii\httpclient\Request 相同的签名。例如:

use yii\httpclient\Client;
use yii\httpclient\RequestEvent;

$client = new Client();

$client->on(Client::EVENT_BEFORE_SEND, function (RequestEvent $event) {
    // ...
});
$client->on(Client::EVENT_AFTER_SEND, function (RequestEvent $event) {
    // ...
});

Note:\yii\httpclient\Client\yii\httpclient\Request 共享 EVENT_BEFORE_SENDEVENT_AFTER_SEND 事件的相同名称,所以你可以创建可以应用于这两个类的行为。

日志与分析

这个扩展允许记录 HTTP 请求被发送的日志和分析他们的执行情况。为了设置一个日志目标,它可以捕获所有与 HTTP 请求相关的条目,你应该使用类目 yii\httpclient\Transport*。例如:

return [
    // ...
    'components' => [
        // ...
        'log' => [
            // ...
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'logFile' => '@runtime/logs/http-request.log',
                    'categories' => ['yii\httpclient\*'],
                ],
                // ...
            ],
        ],
    ],
];

您也可以使用 HTTP 客户端调试面板去查看所有关联的日志,在最后的章节会讲到。

Attention:由于一些 HTTP 请求的内容可能非常长,将其完整保存在日志中可能会导致某些问题。因此,对请求内容的最大长度有限制,这些内容将被放置在日志中。这是通过 \yii\httpclient\Client::$contentLoggingMaxSize 属性控制的。任何超出的内容将在日志记录之前被裁剪。

设置客户端实例

我们可以从实例化 yii\httpclient\Client 对象开始,使用这个扩展。有几种方法可以将 yiii\httpclient\Client 集成到你的程序中。这里描述了最常见的方法。

作为应用组件

\yii\httpclient\Client 继承 \yii\base\Component,因此,它可以在 \yii\di\Container 级别设置,作为模块或应用程序组件。例如:

return [
    // ...
    'components' => [
        // ...
        'phpNetHttp' => [
            'class' => 'yii\httpclient\Client',
            'baseUrl' => 'http://uk.php.net',
        ],
    ],
];

// ...
echo Yii::$app->phpNetHttp->get('docs.php')->send()->content;

扩展客户端类

自从 \yii\httpclient\Client 可以用作应用程序组件,你就可以扩展它,添加一些你需要的自定义逻辑。例如:

use yii\httpclient\Client;

class MyRestApi extends Client
{
    public $baseUrl = 'http://my.rest.api/';

    public function addUser(array $data)
    {
        $response = $this->post('users', $data)->send();
        if (!$response->isOk) {
            throw new \Exception('Unable to add user.');
        }
        return $response->data['id'];
    }

    // ...
}

包装客户端对象

你可以使用 \yii\httpclient\Client 实例作为组件的内部字段,它提供了一些复杂的功能。例如:

use yii\base\Component;
use yii\httpclient\Client;

class MyRestApi extends Component
{
    public $baseUrl = 'http://my.rest.api/';

    private $_httpClient;

    public function getHttpClient()
    {
        if (!is_object($this->_httpClient)) {
            $this->_httpClient = Yii::createObject([
                'class' => Client::className(),
                'baseUrl' => $this->baseUrl,
            ]);
        }
        return $this->_httpClient;
    }

    public function addUser(array $data)
    {
        $response = $this->getHttpClient()->post('users', $data)->send();
        if (!$response->isOk) {
            throw new \Exception('Unable to add user.');
        }
        return $response->data['id'];
    }

    // ...
}

使用 HTTP 客户端调试面板

Yii 2 HTTP 客户端扩展提供了一个调试面板,可以与 Yii 2 调试模块集成,显示执行的 HTTP 请求。

在你的应用程序配置中添加以下内容来启用它,如果你已经启用了调试模块,只需要添加面板配置就足够了。具体如下:

    // ...
    'bootstrap' => ['debug'],
    'modules' => [
        'debug' => [
            'class' => 'yii\\debug\\Module',
            'panels' => [
                'httpclient' => [
                    'class' => 'yii\\httpclient\\debug\\HttpClientPanel',
                ],
            ],
        ],
    ],
    // ...

此面板允许您执行已记录的 HTTP 请求以查看其响应。您可以以文本形式获得响应,也可以直接将其传递给浏览器。

Note:只有常规记录的HTTP请求可以通过调试面板执行,批量发送的请求不能。还要记住,日志请求的内容可以根据 yii\httpclient\Client::$contentLoggingMaxSize 属性进行修剪,所以它的执行可能会失败或产生意想不到的结果。

💖喜欢本文档的,欢迎点赞、收藏、留言或转发,谢谢支持!
作者邮箱:zhuzixian520@126.com,github地址:github.com/zhuzixian520

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
zhuzixian520
讨论数量: 0
发起讨论 只看当前版本


暂无话题~