在POST urlencoded时接收JSON响应

时间:2016-03-01 19:04:15

标签: php json post

我希望在POST提交urlencoded请求后接收并解码JSON响应 但是我在下面运行后获得的所有内容($ content)都是乱码 我相信服务器返回正确的值(我通过hurl.it检查)

PHP代码如下。

$target_url = "http://examples.com/send";]
$headers = array(
    'Host: examples.com',
    'Content-Type: application/x-www-form-urlencoded; charset=utf-8',
    'Accept-Language: en-us',
    'Accept-Encoding: gzip, deflate',
    'User-Agent: Appcelerator Titanium/3.5.0',
);
$data = array(
    'id' => 'hogehoge',
    'command' => 'renew'
);

$options = array('http' => array(
    'method' => 'POST',
    'content' => http_build_query($data),
    'header' => implode("\r\n", $headers),
));

$contents = file_get_contents($target_url, false, stream_context_create($options));
echo $contents;

回复的标题是

Connection: keep-alive
Content-Encoding: gzip
Content-Length: 32
Content-Type: application/json; charset=utf-8
Date: ***** GMT
Server: Apache
Vary: Accept-Encoding,User-Agent

当我回复$ contents时,我得到了

�ォV*J-.ヘ)Qイ2ャワゥp0

虽然它应该是

{"result":1}

提前致谢。

ADD: 当我var_dump(json_decode($contents))时,我得到NULL

3 个答案:

答案 0 :(得分:0)

作为回应,服务器通知您它正在发送压缩内容,您必须将其解压缩。

Content-encoding: gzip

您可以使用gzdecode()解压缩gzip。

echo gzdecode($content);

答案 1 :(得分:0)

解压缩内容:

echo gzdecode($contents);

答案 2 :(得分:0)

您正在接收标题Content-Encoding: gzip所指示的gziped字符串。

您可以使用php或js解压缩它。

http://php.net/manual/en/function.gzdecode.php

https://github.com/gcanu/gzip.js