php从http帖子中读取json结果

时间:2015-07-07 19:16:43

标签: php json

我对服务器进行HTTP POST,并且我试图从结果中获取session_token的值,我该怎么做?

我的帖子:

curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt( $ch, CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: POST','Content-Type:application/x-www-form-urlencoded','Content-Length: ' . strlen(http_build_query($data))));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec( $ch );
print_r($response);

回应:

HTTP/1.1 200 OK
Date: Tue, 07 Jul 2015 19:12:25 GMT
Server: Apache/2.4.10 (Win32) OpenSSL/1.0.1i mod_wsgi/3.5 Python/2.7.8
Content-Length: 180
Content-Type: application/json

{"guid": null, "session_token": "0kndD67A0dptosqodpSuCUoAsrNxTxnMqme29Grkx0sKaXEKH3wYAis6arOkH4ETHf6ytC8UNotBhwsPM61jJWqnX1mXbhBFlJI8z56yBA6dPUVaynta0LvrNUgZxwc5", "success": true}

我尝试过json_decode但返回null。

2 个答案:

答案 0 :(得分:2)

关闭/删除这些选项:

curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

他们导致http响应标头包含在$response中,这使得您的响应成为"随机的http相关文本+ json"而不仅仅是" JSON"

答案 1 :(得分:0)

由于curl_setopt($ch, CURLOPT_HEADER, 1);curl_exec()会返回完整的响应消息(标题和正文)。您可以删除CURLOPT_HEADER选项(并仅接收正文)或保留请求,并解析返回的内容以标识标题(如果您需要验证它们)和正文。或者,您可以配置curl以在已打开的文件中返回标题,并获取标题和正文但已经拆分。

对于第二个选项(让请求原样并解析返回的内容以分隔正文的标题),您可以使用curl_getinfo()找出响应标题的大小:

$response = curl_exec($ch);
$info     = curl_getinfo($ch);

// Split the headers and the body
$headers = substr($response, 0, $info['header_size'];
$body    = substr($response, $info['header_size']);

// The body is encoded as JSON (should verify this in the headers)
$pieces = json_decode($body, TRUE);

// Here, if $pieces is not NULL (it happens when json_decode() fails)
// it should be
//     array(
//         'guid' => NULL,
//         'session_token' => '0kndD67A0dptosqodpSuCUoAsrNxTxnMqme29Grkx0sKaXEKH3wYAis6arOkH4ETHf6ytC8UNotBhwsPM61jJWqnX1mXbhBFlJI8z56yBA6dPUVaynta0LvrNUgZxwc5',
//         'success' => TRUE,
//     )