使用ZendFramework2请求Random.org API

时间:2015-01-01 07:54:39

标签: php json zend-framework2

我对ZF2很新,我想用外部API创建一些应用程序。我已成功创建了向random.org API发送请求的方法,但作为响应,它向我发送了与解析相关的错误。我不知道我做错了什么以及如何改进我的方法以获得适当的数据作为响应。

这是我用来发送请求的方法(我故意更改了api密钥,在我的应用程序中我正在使用正确的密码):

public function makeRequest()
{
    $data = array(
        'jsonrpc' => '2.0',
        'method' => 'generateIntegers',
        'params' => array(
            'apiKey' => '00000000-0000-0000-0000-000000000000',
            'n' => 10,
            'min' => 1,
            'max' => 10,
            'replacement' => true,
            "base" => 10),
        'id' => 23866,
    );

    $client = new Client('https://api.random.org/json-rpc/1/invoke', array(
        'adapter' => 'Zend\Http\Client\Adapter\Curl'
    ));
    $client->setEncType(Client::ENC_FORMDATA);

    $request = new Request();
    $request->setUri('https://api.random.org/json-rpc/1/invoke');
    $request->setMethod('POST');
    $request->getPost()->fromString(json_encode($data));
    $response = $client->send($request);

    return $response;
}

以下是回复的内容:

["content":protected]=> string(87) "{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":null},"id":null}

1 个答案:

答案 0 :(得分:2)

来自ZF2 Request Reference,您可以找到setContent()功能,您可以尝试而不是getPost()->fromString()吗?

public function makeRequest()
{
    $data = array(
        'jsonrpc' => '2.0',
        'method' => 'generateIntegers',
        'params' => array(
            'apiKey' => '00000000-0000-0000-0000-000000000000',
            'n' => 10,
            'min' => 1,
            'max' => 10,
            'replacement' => true,
            "base" => 10),
        'id' => 23866,
    );

    $client = new Client('https://api.random.org/json-rpc/1/invoke', array(
        'adapter' => 'Zend\Http\Client\Adapter\Curl'
    ));
    $client->setEncType(Client::ENC_FORMDATA);

    $request = new Request();
    $request->setUri('https://api.random.org/json-rpc/1/invoke');
    $request->setMethod('POST');


    //$request->getPost()->fromString(json_encode($data));
    $request->setContent(json_encode($data));

    $response = $client->send($request);

    return $response;
}