简体   繁体   中英

Receive JSON response while POST urlencoded

I want to receive and decode JSON response after submitting urlencoded request by POST.
But all I got ($content) after running below is garbled characters.
I believe the server returns correct values (I checked via hurl.it)

PHP code is below.

$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;

Headers of response is

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

When I echo $contents, I got

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

although it should be

{"result":1}

Thanks in advance.

ADD: When I var_dump(json_decode($contents)) ,I got NULL

In response, server is informing you that it is sending zipped content, you must unzip it.

Content-encoding: gzip

You can use gzdecode() to unzip gzip.

echo gzdecode($content);

解压缩内容:

echo gzdecode($contents);

You are receiving a gziped string as pointed by the header Content-Encoding: gzip .

You can uncompress it using php or js.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM