Loader.io - PHP,curl和json

时间:2016-09-19 10:46:57

标签: php curl php-7

我正在为客户评估loader.io,但是我遇到了让APi正常工作的问题。我正在使用PHP 7 http://docs.loader.io/api/v2/post/tests.html#url-options

我坚持'创建测试'。

文档说:

curl -X POST -H 'loaderio-auth: API_KEY' -H 'Content-Type: application/json' --data-binary '{"test_type":"cycling",               "total": 6000,               "duration":60,               "urls": [                 {"url": "http://gonnacrushya.com"} ]}' https://api.loader.io/v2/tests

太棒了!当我添加我的APi密钥和正确的URL时,它运行得很好,就会创建测试。

Buuuut ..

我想通过Symfony2应用程序在ajax中执行此操作。

这就是我所得到的错误:

urls param has incorrect format

function myAjaxCalledFunction() {
    $test_data = '{"test_type":"cycling", "total": 10, "duration":5, "urls": [{"url": "http://www.my-configured-url.com"}] }';
    return $this->doCurlRequest('tests', 'POST', $test_data);
}


public function doCurlRequest($what_call, $request = 'GET', $post_data = null)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.loader.io/v2/' . $what_call);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('loaderio-auth: ' . $this->loader_api_key));

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
    curl_setopt($ch, CURLOPT_POST,           1 );
    curl_setopt($ch, CURLOPT_POSTFIELDS,     $post_data );
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    $response = curl_exec($ch);
    return new Response($response);
 }

我缺少一个curl_setopt()吗?

1 个答案:

答案 0 :(得分:1)

您要设置选项CURLOPT_HTTPHEADER两次。这就是它忽略第一个原因的原因。你可以将它们推入数组,如下例所示:

curl_setopt($ch, CURLOPT_HTTPHEADER, 
    array('loaderio-auth: ' . $this->loader_api_key,
          'Content-type: application/json'));