Home >Backend Development >PHP Tutorial >HTTP client library in PHP8.0

HTTP client library in PHP8.0

WBOY
WBOYOriginal
2023-05-14 08:51:401774browse

HTTP client library in PHP8.0

The release of PHP8.0 brings many new features and improvements, one of the most eye-catching is the addition of the built-in HTTP client library. This library provides a simple way to send HTTP requests and handle the returned responses. In this article, we will explore the main features and usage of this library.

Send HTTP requests

It is very simple to send HTTP requests using the built-in HTTP client library of PHP8.0. In this example, we will use the GET method to get the homepage of this website:

use HttpClientExceptionHttpException;
use HttpClientHttpClient;
use HttpMessageRequestFactory;
use HttpMessageStreamFactory;

require_once "vendor/autoload.php";

// Create the client
$httpClient = HttpClientDiscovery::find();

// Create the request
$requestFactory = new RequestFactory();
$request = $requestFactory->createRequest(
    'GET',
    'http://example.com'
);

// Send the request and wait for the response
try {
    $response = $httpClient->sendRequest($request);
} catch (HttpException $e) {
    echo 'Error: ' . $e->getMessage();
    exit;
}

// Print the response body
$body = (string) $response->getBody();
echo $body;

In this example, we first use the factory class method HttpClientDiscovery::find() to create an HTTP client . Then, use the RequestFactory::createRequest() method to create an HTTP request, specifying the request method and request URL. Finally, use the HttpClient::sendRequest() method to send the request and wait for the response. If the request fails to be sent, an HttpException exception will be thrown.

Processing the response

After receiving the response, we can use the HTTP response object to access the response status, response headers, and response body. In the code below, we will print a string representing the response status, response headers, and response body.

use HttpMessageResponseFactory;

$responseFactory = new ResponseFactory();
$status = $response->getStatusCode();
$headers = $response->getHeaders();
$body = (string) $response->getBody();

$responseString = sprintf(
    "HTTP/%s %s
%s

%s",
    $response->getProtocolVersion(),
    $status,
    implode("
", $headers),
    $body
);

echo $responseString;

Here, we use the ResponseFactory::createResponse() method to create an HTTP response object. Then, use the methods provided by the ResponseInterface interface to access the response status, response headers, and response body. Finally, we combine the response into a string and print it on the screen.

Handling the response body

When we send an HTTP request and receive a response from the server, we can also process the response body. Let's take a look at how to process the JSON response body:

use HttpMessageJsonResponseFactory;

$responseFactory = new JsonResponseFactory();
$decoded = $responseFactory->createResponse($response)->getPayload();

echo 'The decoded response is:' . PHP_EOL;
print_r($decoded);

In this example, we use the JsonResponseFactory::createResponse() method to create a JSON-formatted HTTP response object. Then, use the getPayload() method provided by the JsonResponseInterface interface to decode the JSON response body. Finally, we print the decoded response body to the console.

Handling Exceptions

When using the HTTP client library, sometimes requests may fail, possibly due to network connection errors or server failures. When this happens, the HTTP client library will throw an HttpException exception. In the following code snippet, we will catch this exception and print out the error message.

use HttpClientExceptionHttpException;

// ...

try {
    $response = $httpClient->sendRequest($request);
} catch (HttpException $e) {
    echo 'Error: ' . $e->getMessage();
    exit;
}

If an exception occurs, an error message will be displayed and the program will exit. This allows us to take appropriate action if a request fails, such as printing an error message or retrying the request.

Conclusion

The HTTP client library is an important new feature in PHP8.0. It provides a powerful way to send HTTP requests and handle responses. In this article, we have introduced the main functions and usage of the HTTP client library, including sending HTTP requests, processing responses, processing response bodies, and handling exceptions. Now, we can use the HTTP client library in our PHP application.

The above is the detailed content of HTTP client library in PHP8.0. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn