首页 文章

ZF2 RESTful JsonModel

提问于
浏览
1

我使用PHP-cURL(在WP-Plugin中)从我的ZF2应用程序获取JSON响应 .

我要做2个请求 .

  • OAuth

  • GET请求

第一个工作正常我只是得到了json_encoded数组 . 但是,当我发送GET请求时,响应看起来像(本地的一切):

plugin.php:16:string'HTTP / 1.1 200 OK日期:星期五,2016年11月18日13:14:20 GMT服务器:Apache / 2.4.23(Win32)OpenSSL / 1.0.2h PHP / 7.0.9 X-Powered -By:PHP / 7.0.9 Set-Cookie:PHPSESSID = gb99a214u3rlc125ca4rscd441; expires = Fri,2016年11月18日23:14:20 GMT;最大年龄= 36000; path = / Expires:Thu,19 Nov 1981:08:52:00 GMT Cache-Control:no-store,no-cache,must-revalidate Pragma:no-cache Transfer-Encoding:chunked Content-Type:application / json; charset = utf-8 {“data”:{“Machines”:[{“ID”:2590978,“Refnummer”:1000869,“Maschinentyp”:“504”'...(长度= 41759)

为什么我会得到完整的响应头?如果我现在尝试json_decode它我必须事先摆脱所有 Headers 的东西,我可以避免吗?

这就是我生成响应的方式

$server = call_user_func($this->oauthServerFactory, $this->params('oauth'));
if (!$server->verifyResourceRequest(OAuth2Request::createFromGlobals())) {
    // Not authorized return 401 error
    $this->getResponse()->setStatusCode(401);
    return $this->getResponse();
}

//GET DATA

$jsonArray = array();
$jsonArray['Machines'] = array();
$jsonMachinesArray = array();
foreach ($machines as $machine)
{
    //ORDER DATA
}

return new JsonModel(array(
    'data'  => $jsonArray
));

在这里我创建了请求:

$endpoint = $url;
//var_dump($access_token);
$headers = array(
    'Content-Type: application/json',
    'Authorization: Bearer '.$access_token,
);
$curl = curl_init($endpoint);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

echo "Performing Request...<br>";

$json_response = curl_exec($curl);
//var_dump($json_response);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

// evaluate for success response
if ($status != 200) {
    throw new Exception("Error: call to URL $endpoint failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl) . "\n");
}
curl_close($curl);

return $json_response;

1 回答

相关问题