当前位置: 首页 > 工具软件 > Guzz > 使用案例 >

php guzzle 上传文件,Guzzle 使用文档

林德惠
2023-12-01

安装

composer require guzzlehttp/guzzle:7.0.1

发起 Get 请求

use GuzzleHttp\Client as guzzleClient;

$guzzleClient = new guzzleClient([

'timeout' => 2.0

]);

// 同步请求方式

$response = $guzzleClient->get('http://api.org/get', ['headers' => ['User-Agent' => 'Guzzle'], 'http_errors' => false]);

$code = $response->getStatusCode();

$body = $response->getBody();

$content = $body->getContents();

// 异步请求方式

$promise = $guzzleClient->getAsync('http://api.org/get');

$promise->then(

function (ResponseInterface $res) {

echo $res->getStatusCode() . "\n";

},

function (RequestException $e) {

echo $e->getMessage() . "\n";

echo $e->getRequest()->getMethod();

}

);

发起 Post 请求

use GuzzleHttp\Client as guzzleClient;

$guzzleClient = new guzzleClient([

'timeout' => 2.0

]);

// 原始类型

$response = $guzzleClient->post('http://api.org/post', [

'body' => 'raw data'

]);

// json 类型 application/json

$response = $guzzleClient->post('http://api.org/post', [

'json' => ['name' => 'admin']

]);

// 表单类型 application/x-www-form-urlencoded

$response = $guzzleClient->post('http://api.org/post', [

'form_params' => [

'username' => 'abc',

'password' => '123'

]

]);

// 上传文件 multipart/form-data

$response = $guzzleClient->post('http://api.org/post', [

'multipart' => [

[

'name' => 'user',

'contents' => 'admin'

],

[

'name' => 'file',

'contents' => fopen('/path/to/file', 'r')

],

]

]);

 类似资料: