PHP code example of phpdevcommunity / php-httpclient

1. Go to this page and download the library: Download phpdevcommunity/php-httpclient library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phpdevcommunity / php-httpclient example snippets


use PhpDevCommunity\HttpClient\HttpClient;

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

// Perform a GET request
$response = $client->get('/api/data');

if ($response->getStatusCode() === 200) {
    echo $response->getBody(); // Raw response body
    print_r($response->bodyToArray()); // JSON decoded response
}

$response = $client->get('/api/search', ['query' => 'test']);

$data = [
    'username' => 'testuser',
    'password' => 'secret'
];

$response = $client->post('/api/login', $data);

$data = [
    'title' => 'Hello World',
    'content' => 'This is a post content'
];

$response = $client->post('/api/posts', $data, true); // `true` specifies JSON content type

$client = new HttpClient([
    'base_url' => 'http://example.com',
    'headers' => ['Authorization' => 'Bearer your_token']
]);

$response = $client->get('/api/protected');

$client = http_client([
    'base_url' => 'http://example.com',
    'headers' => ['Authorization' => 'Bearer your_token']
]);

$response = http_post('http://example.com/api/login', [
    'username' => 'user123',
    'password' => 'secret'
]);

$response = http_post_json('http://example.com/api/create', [
    'title' => 'New Post',
    'body' => 'This is the content of the new post.'
]);

$response = http_get('http://example.com/api/users', [
    'page' => 1,
    'limit' => 10
]);

// Make a GET request
$response = http_get('http://api.example.com/items', ['category' => 'books']);
$data = $response->bodyToArray();

// Make a POST request with form data
$response = http_post('http://api.example.com/login', [
    'username' => 'user123',
    'password' => 'secret'
]);

// Make a POST request with JSON data
$response = http_post_json('http://api.example.com/posts', [
    'title' => 'Hello World',
    'content' => 'This is my first post!'
]);
bash
composer