2016-03-01 71 views
1

我想在POST提交urlencoded请求后接收和解码JSON响应。
但我在下面运行后得到的($ content)是乱码。
我相信服务器返回正确的值(我通过hurl.it检查)POST时接收JSON响应urlencoded

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 

当我回声$内容,我

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

尽管它应该是提前

{"result":1} 

感谢。

地址: 当我var_dump(json_decode($contents)),我得到了NULL

+1

'gzip'你必须将它解压缩。 – AbraCadaver

+1

注意:'内容编码:gzip'。你得到了json,它只是gzipped。 –

+0

'$ target_url =“http://examples.com/send”;]'我认为它必须是'$ target_url =“http://examples.com/send”;'可能是TYPO? –

回答

0

在响应,服务器通知您正在发送压缩的内容,则必须将其解压缩。

Content-encoding: gzip 

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

echo gzdecode($content); 
+0

刚刚发现这个http://stackoverflow.com/questions/8895852/uncompress-gzip-compressed-http-response –

0

解压内容:

echo gzdecode($contents);