问题描述
我对 ZF2 很陌生,我想使用外部 API 创建一些应用程序.我已经成功创建了向 random.org API 发送请求的方法,但作为响应,它向我发送了一个与解析相关的错误.我不知道我做错了什么,也不知道如何改进我的方法来获得正确的响应数据.
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.
这是我用于发送请求的方法(我有意更改了 api 密钥,并且在我的应用中使用了正确的密钥):
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;
}
这里是回复的内容:
["content":protected]=> string(87) "{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error","data":null},"id":null}
推荐答案
from ZF2 请求参考,你可以找到 setContent()
函数,你可以试试用它代替 getPost()->fromString()
?
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;
}
这篇关于使用 ZendFramework2 请求 Random.org API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!