PHP cURL转换为Guzzle

时间:2015-09-04 12:04:43

标签: php symfony curl guzzle

我正致力于与sentione api集成。 我有guzzle的问题,guzzle扔给我401未经授权的例外。 我认为这可能是发布数据的问题,我试图以另一种方式设置它,但我总是得到相同的结果。

那是我的代码:

        $arr = array(
            'topicId' => id, 
            'from' => '2014-01-01 00:00:00.000 CET'
        );
        $params = json_encode($arr);

        $client = new Client('http://sentione.com/api', array(
            'request.options' => array(
                'headers' => array(
                        "Accept: application/json",        
                        "X-API-KEY: key",
                        "Content-type: application/json",
                    )
                )
        ));

        $request = $client->post('statements/search', array('Content-Type' => 'application/json'), $params);
        $response = $request->send();

那是我的cURL定义:

$arr = array(
    "topicId" => id, 
    "from" => "2014-01-01 00:00:00.000 CET"
);

$json = json_encode($arr);

$headers = array(
        "Accept: application/json",        
        "X-API-KEY: key",
        "Content-type: application/json",
);
$url = "http://sentione.com/api/statements/search";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
$response = curl_exec($curl); 

当然,它运作得很好。 有人可以帮帮我吗?也许我忘记了?

1 个答案:

答案 0 :(得分:0)

我认为问题在于这个结构:

    $client = new Client('http://sentione.com/api', array(
        'request.options' => array(
            'headers' => array(
                    "Accept: application/json",        
                    "X-API-KEY: key",
                    "Content-type: application/json",
                )
            )
    ));

在创建请求的过程中,有关于Guzzle客户端版本之间差异的信息。 点击这里:

https://github.com/guzzle/guzzle/issues/777

Why is my Authorization Header giving me a 401 in Guzzle?