Loader.io - PHP、curl 和 json

Loader.io - PHP, curl and json

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

我卡在 'create test'。

文档说:

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()?

您正在设置选项 CURLOPT_HTTPHEADER 两次。这就是为什么它忽略了第一个。您可以将它们都推入数组,如下例所示:

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