-
Notifications
You must be signed in to change notification settings - Fork 5
HTTP Request
POST
The Http
class is located in Monster\App\Models\Http.php
. It is a simple PHP class for making HTTP requests using cURL.
The constructor initializes a new cURL handle and sets default options.
$http = new Http();
This method adds a single HTTP header to the request.
$http->Header('Content-Type: application/json');
This method sets the HTTP headers for the request.
$http->Headers(['Content-Type: application/json', 'Authorization: Bearer token']);
This method sets a cURL option for the request.
$http->Option(CURLOPT_RETURNTRANSFER, true);
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
]);
This method sets the request timeout in seconds.
$http->Timeout(30);
This method sets the URL for the request.
$http->Url('https://example.com/api/users');
This method sets the HTTP method for the request (e.g. "GET", "POST", etc.)
$http->Method('GET');
This method sets the request body for the request.
$http->Body(json_encode(['name' => 'John Doe', 'email' => 'john@example.com']));
This method sends the HTTP request and returns the response.
$response = $http->Send();
This method returns the HTTP status code of the response.
$status = $http->getStatus();
The destructor closes the cURL handle when the object is destroyed.
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.
To continue with the documentation and examples of HTTP requests, refer to the HTTPMonster repository at https://github.com/ReactMVC/HTTPMonster. However, in the API-Monster framework, use "Http" as the class name instead of HTTPMonster.
- 1 - Installation
- 2 - Routing And Database
- 3 - HTTP Request
- 4 - CORS
- 5 - Env File
- 6 - Views
- 7 - Language
- 8 - SPA Without API
- 9 - Data Validation
- 1 - Installation
- 2 - Routing And Database
- 3 - HTTP Request
- 4 - CORS
- 5 - Env File
- 6 - Views
- 7 - Language
- 8 - SPA Without API
- 9 - Data Validation