hyperf遇到的坑-http请求无返回值GuzzleHttp

解决无http返回值这样写就可以收到返回值了

use GuzzleHttp\Client;
use Hyperf\Guzzle\CoroutineHandler;
use GuzzleHttp\HandlerStack;

class{
function index(){
$factory = new HandlerStackFactory();
        $stack = $factory->create();

        $client = make(Client::class, [
            'config' => [
                'base_uri' => 'http://111.231.70.84:9501',
                'timeout' => 5,
                'swoole' => [
                    'timeout' => 10,
                    'socket_buffer_size' => 1024 * 1024 * 2,
                ],
                'handler' => $stack,
            ],
        ]);  
        $response = $client->get('/',['id'=>1]);
        $server->push($request->fd,'response:'.$response->getBody()->getContents());
}

}

post请求
use GuzzleHttp\Client;

  public function post($url, $param = array())
    {
        $client = new Client();
        $response = $client->request('POST', $url,["json"=>$param]);
        echo $response->getBody();
}

返回的是json字符串

Cannot use object of type stdClass as array

产生原因:


$res = json_decode($res);
$res['key']; //把 json_decode() 后的对象当作数组使用。

解决方法(2种):

1、使用 json_decode(d, true)。就是使json_decode 的第二个变量设置为 true。 2、json_decode(res) 返回的是一个对象, 不可以使用 res['key'] 进行访问, 换成res->key 就可以了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。