2016-03-01 69 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);