Skip to content

HTTP Request

Hossein Pira edited this page Aug 3, 2023 · 4 revisions

Http Class

POST The Http class is located in Monster\App\Models\Http.php. It is a simple PHP class for making HTTP requests using cURL.

Constructor

The constructor initializes a new cURL handle and sets default options.

$http = new Http();

Methods

Header

This method adds a single HTTP header to the request.

$http->Header('Content-Type: application/json');

Headers

This method sets the HTTP headers for the request.

$http->Headers(['Content-Type: application/json', 'Authorization: Bearer token']);

Option

This method sets a cURL option for the request.

$http->Option(CURLOPT_RETURNTRANSFER, true);

Setting Multi Options

Sets default cURL options for the request. You can modify these defaults by calling the setDefaults() method:

$http->setDefaults([
    CURLOPT_SSL_VERIFYHOST => 2,
    CURLOPT_SSL_VERIFYPEER => true
]);

Timeout

This method sets the request timeout in seconds.

$http->Timeout(30);

Url

This method sets the URL for the request.

$http->Url('https://example.com/api/users');

Method

This method sets the HTTP method for the request (e.g. "GET", "POST", etc.)

$http->Method('GET');

Body

This method sets the request body for the request.

$http->Body(json_encode(['name' => 'John Doe', 'email' => 'john@example.com']));

Send

This method sends the HTTP request and returns the response.

$response = $http->Send();

getStatus

This method returns the HTTP status code of the response.

$status = $http->getStatus();

Destructor

The destructor closes the cURL handle when the object is destroyed.

Full Example

Here is an example of how you can use the Http class in a controller:

<?php

namespace Monster\App\Controllers;

use Monster\App\Models\Http;

class Test
{
    public function index()
    {
        $http = new Http();

        $http->Url('https://example.com/api/users')
             ->Method('POST')
             ->Headers(['Content-Type: application/json', 'Authorization: Bearer token'])
             ->Body(json_encode(['name' => 'John Doe', 'email' => 'john@example.com']))
             ->Timeout(30);

        $response = $http->Send();

        if ($http->getStatus() === 200) {
            // Request was successful
            echo "Response: " . $response;
        } else {
            // Request failed
            echo "Error: " . $response;
        }
    }
}

This index method makes a POST request to 'https://example.com/api/users' with a JSON payload, and then checks the status code of the response to determine if the request was successful.

Clone this wiki locally