valmaraz/php-network

网络 - 用于发送HTTP请求的轻量级库

v0.0.2 2017-01-28 20:39 UTC

This package is not auto-updated.

Last update: 2024-09-28 20:25:26 UTC


README

Packagist Packagist Packagist

Network是一个用于发送HTTP请求的轻量级库。

安装

composer require vAlmaraz/php-network

用法

use vAlmaraz\network\Network;

// Set URL and execute request
$response = Network::get($url)->execute();

// Retrieve response
echo $response->getBody();

高级用法

use vAlmaraz\network\Network;

$timeoutInSeconds = 3;
$headers = ['Accept' => 'application/json'];
$formData = ['field1' => 'value1', 'field2' => 'value2'];

// Configure request
$response = Network::post($url)
    ->setTimeoutInSeconds($timeoutInSeconds)
    ->withHeaders($headers)
    ->withFormData($formData)
    ->execute();

// Retrieve response info
echo $response->getStatusCode();
echo json_encode($response->getHeaders());
echo $response->getBody();

示例

use vAlmaraz\network\Network;

$network = new Network();
// GET
$response = $network->get('https://jsonplaceholder.typicode.com/posts')
    ->execute();
// POST
$response = $network->post('https://jsonplaceholder.typicode.com/posts')
    ->withFormData(['title' => 'My title', 'body' => 'The body', 'userId' => 123])
    ->execute();
// PATCH
$response = $network->patch('https://jsonplaceholder.typicode.com/posts/1')
    ->withFormData(['title' => 'A new title'])
    ->execute();
// PUT
$response = $network->put('https://jsonplaceholder.typicode.com/posts/1')
    ->withFormData(['title' => 'My title', 'body' => 'The body', 'userId' => 123])
    ->execute();
// DELETE
$response = $network->delete('https://jsonplaceholder.typicode.com/posts/1')
    ->execute();

echo 'Status code: ' . $response->getStatusCode() . PHP_EOL . PHP_EOL;
echo 'Headers: ' . json_encode($response->getHeaders()) . PHP_EOL . PHP_EOL;
echo 'Body: ' . $response->getBody();

许可证

本项目采用MIT许可证。有关更多信息,请参阅LICENSE文件。