Request to Random.org API with ZendFramework2

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-23 22:21:01

问题


I'm quite new to ZF2 and I wanted to create some app utilizing external API. I have successfully created method to send requests to random.org API but as a response it sends me an error connected with parsing. I have no idea what I'm doing wrong and how to improve my method to get proper data in response.

Here is my method used to send request (I have intentionally changed api key and in my app I'm using the proper one):

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;
}

And here is the content of response:

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

回答1:


from ZF2 Request Reference, you can find setContent() function, could you try that instead of 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;
}


来源:https://stackoverflow.com/questions/27729171/request-to-random-org-api-with-zendframework2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!