将其转换为使用Guzzle不起作用

时间:2019-10-09 07:14:52

标签: php http fopen guzzle

我具有以下SDK上当前用于集成的代码,我希望将其迁移到使用Guzzle PHP以获得更简洁的代码。

<?php

class Request
{
    private $is_last_session_id;

    public function send($s_url, $data)
    {

        $params = [
            'http' => [
                'method'  => 'POST',
                'content' => $data,
                'header'  => "Content-type: application/x-www-form-urlencoded",
            ],
        ];

        $ctx = stream_context_create($params);

        ini_set('user_agent', 'PHP Client /5.2.00');

        $fp = fopen($s_url, 'rb', false, $ctx);

        $response = stream_get_contents($fp);

        $meta = stream_get_meta_data($fp);

        foreach (array_keys($meta) as $h) {
            $v = $meta[$h];
            if (is_array($v)) {
                foreach (array_keys($v) as $hh) {
                    $vv = $v[$hh];
                    if (is_string($vv) && substr_count($vv, 'JSESSIONID')) {
                        $this->is_last_session_id = substr($vv, strpos($vv, '=') + 1, 24);
                    }
                }
            }
        }

        return $response;
    }
}

这是使用Guzzle的代码

    private function guzzleRequest($uri, $data)
    {
        $client = new \GuzzleHttp\Client();

        $client->request('POST', $uri, [
            'form_params' => $data,
            'headers'     => [
                'Content-type' => 'application/x-www-form-urlencoded',
            ],
        ]);
    }

从代码中,我知道它正在执行POST请求,但是当我尝试将Guzzle的$client->post()$client->request('POST',$data)与上述代码中的特定标头一起使用时,我得到了500台服务器错误。上面的代码是正常的。使用Guzzle调用方法时我会丢失某些东西吗?

1 个答案:

答案 0 :(得分:0)

这应该很简单:

$client = new \GuzzleHttp\Client();
$client->request('POST', $uri, ['form_params' => $data]);