PHP:使用guzzlehttp/guzzle的方式
我在Ubuntu 23.04上进行了与下一页相同的操作。
使用PHP的Http客户端库Guzzle包。
安装图书馆
composer require guzzlehttp/guzzle
已创建的 composer.json
{
"require": {
"guzzlehttp/guzzle": "^7.8"
}
}
测试程序
#! /usr/bin/php
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('GET', 'https://jsonplaceholder.typicode.com/posts/1');
echo $response->getBody();
?>
执行结果
$ ./check01.php
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
使用Httpie发出相同的请求
$ http https://jsonplaceholder.typicode.com/posts/1
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Age: 5591
CF-Cache-Status: HIT
CF-RAY: 80b9bf0be94df583-NRT
Cache-Control: max-age=43200
Connection: keep-alive
Content-Encoding: gzip
Content-Type: application/json; charset=utf-8
Date: Sun, 24 Sep 2023 08:44:34 GMT
Etag: W/"124-yiKdLzqO5gfBrJFrcdJ8Yq0LGnU"
Expires: -1
NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800}
Pragma: no-cache
Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=q4EGse%2F7X%2FKbBpDTbGwWcY2%2B5dz%2Bn1cPOE7P31KLFzztbanJdUjgxHe8KIwVnkYQE%2FXFMCQzT54vUngzwkhrKBVcLAmw1txwShE4Ck23bDYTLiJGmRjUleDUOEzULFOkXRKq6tJAKec1PaSCWRB1Xqm2X%2FY2e4h8WsaR"}],"group":"cf-nel","max_age":604800}
Server: cloudflare
Transfer-Encoding: chunked
Vary: Origin, Accept-Encoding
Via: 1.1 vegur
X-Content-Type-Options: nosniff
X-Powered-By: Express
X-Ratelimit-Limit: 1000
X-Ratelimit-Remaining: 999
X-Ratelimit-Reset: 1691790101
alt-svc: h3=":443"; ma=86400
{
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto",
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"userId": 1
}
确认的版本 de
$ php --version
PHP 8.1.12-1ubuntu4.3 (cli) (built: Aug 17 2023 17:37:48) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.12, Copyright (c) Zend Technologies
with Zend OPcache v8.1.12-1ubuntu4.3, Copyright (c), by Zend Technologies