PSR-7 HTTP消息接口规范学习代码
PSR-7 HTTP消息接口规范学习代码
本文编写时间:2024-05-11
需求
1、想学习 PSR-7
HTTP 消息接口规范
2、通过在 laravel 的代码中查看其效果。
3、我测试的版本 laravel:10.48,
4、说明,其实和框架毫无关系,只是 laravel 自带了 Guzzle
的库,而 Guzzle
的库完全实现了 PSR-7 的接口
5、为了学习代码,我写个控制器,带两个接口,
代码路由
//这是返回请求信息的。
Route::any('/http/info', [\App\Http\Controllers\Api\HttpController::class,'info']);
// 这是我请求的代码,
Route::any('/http/test', [\App\Http\Controllers\Api\HttpController::class,'test']);
info接口代码。
public function info(Request $request)
{
return json_encode( $request->all() ) .'||'. json_encode( getallheaders() ).'||'.$request->getMethod();
}
第1次,使用标准的 Guzzle 请求。
use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
public function test(Request $request)
{
$client = new Client();
$response = $client->request('POST', 'http://c7/http/info', [
'form_params'=>[
'a'=>1,
]
]);
$body = $response->getBody()->getContents();
return $body;
}
返回如下
{"a":"1"}||{"Content-Length":"3","Host":"c7","Content-Type":"application\/x-www-form-urlencoded","User-Agent":"GuzzleHttp\/7"}||POST
第2次,使用符合 PSR-7
接口的请求对象
public function test(Request $request)
{
$client = new Client();
$uri = 'http://c7/http/info';
$headers=[
'Content-Type'=> 'application/x-www-form-urlencoded'
];
$request = new \GuzzleHttp\Psr7\Request('POST', $uri, $headers, 'a=2');
$response = $client->sendRequest($request);
return $response->getBody()->getContents();
}
返回如下
{"a":"2"}||{"Content-Length":"3","Content-Type":"application\/x-www-form-urlencoded","Host":"c7","User-Agent":"GuzzleHttp\/7"}||POST
第3次,使用符合 PSR-7
接口的请求对象,且使用了其方法。
public function test(Request $request)
{
$client = new Client();
$uri = 'http://c7/http/info';
$request = new \GuzzleHttp\Psr7\Request('POST', $uri);
$request = $request->withBody(Psr7\Utils::streamFor('a=3'));
$request = $request->withHeader('Content-Type', 'application/x-www-form-urlencoded');
$response = $client->sendRequest($request);
return $response->getBody()->getContents();
}
返回如下:
{"a":"3"}||{"Content-Length":"3","Content-Type":"application\/x-www-form-urlencoded","Host":"c7","User-Agent":"GuzzleHttp\/7"}||POST
总结
1、使用 Guzzle
库时,已经发现,直接使用 request 方法是最方便的(即第一次请求的代码),如果使用 sendRequest 来构造PSR-7
接口的请求对象,好麻烦的。
2、如果使用 Laravel 框架,则直接使用 Laravel 封装好的 HTTP 门面方法更方便。
3、本文代码中,3段代码示例的 response 对象,都是实现了 PSR-7
响应接口的对象。
4、实际Guzzle
的 client 对象,也实现了PSR-18
的 HTTP 客户端接口。PSR-18
只一个方法 sendRequest 。
本作品采用《CC 协议》,转载必须注明作者和本文链接