我正在使用 cURL 和 php 来对 API 进行身份验证。
像这样:
$ch = curl_init();
$headers = [];
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $this->body ));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$this->response = json_decode( curl_exec($ch) );
curl_close ($ch);
请求响应的正文包含状态代码,如果请求成功,则包含用户对象。这是一个匿名请求,它在响应标头中返回令牌。
我的问题:
脚本的上述响应为空。
如果我注释掉 CURLOPT_RETURNTRANSFER 选项,那么我会得到我需要的内容,但它会被回显并且响应为 1。
如果我注释掉 CURLOPT_HEADER 选项,那么我只能得到响应的正文。
我尝试过在 http 和 https 之间切换。
我正在使用 PHP-5.5.27。
您在解码时不确定所得到的是 JSON。它很可能不是 JSON,至少不是所有响应。当你使用CURLOPT_HTTPHEADER
响应由以响应标头开头的文本组成,后面可能有一些 JSON。
做类似的事情:
$ch = curl_init();
$headers = [];
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $this->body ));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
$info = curl_getinfo($ch);
$actualResponseHeaders = (isset($info["header_size"]))?substr($response,0,$info["header_size"]):"";
$actualResponse = (isset($info["header_size"]))?substr($response,$info["header_size"]):"";
$this->response = json_decode( $actualResponse );
curl_close ($ch);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)