guzzle 使用

慕嘉运
2023-12-01
get 请求
 public static  function get()
  {
       $client = new \GuzzleHttp\Client();

       $url = 'mytest.test/users';
       $array = [
           'headers' => [],
           'query' => [
               'phone'=>'15622151111'
           ],
           'http_errors' => true #支持错误输出
       ];
       $response = $client->request('GET', $url, $array);
       dump($response->getStatusCode());   #打印响应信息
       dump(json_decode($response->getBody()->getContents()));   #输出结果
   }
post 请求
 public function testPostRequest1(){
	   $client = new \GuzzleHttp\Client();
       $response = $client->request('POST', 'http://mytest.test/user', [
           'json' => [
               'phone' => 15622222222,
               'name' => 'zrt',
           ]
       ]);

       dd($response->getBody());
 }
上传文件
$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://httpbin.org/post', [
    'multipart' => [
        [
            'name'     => 'field_name',
            'contents' => 'abc'
        ],
        [
            'name'     => 'file_name',
            'contents' => fopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'other_file',
            'contents' => 'hello',
            'filename' => 'filename.txt',
            'headers'  => [
                'X-Foo' => 'this is an extra header to include'
            ]
        ]
    ]
]);

点击查看更多详细操作

 类似资料: