【问题标题】:Receive JSON response while POST urlencodedPOST urlencoded 时接收 JSON 响应
【发布时间】:2016-03-01 19:04:14
【问题描述】:

我想在通过 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}

提前致谢。

添加: 当我var_dump(json_decode($contents))时,我得到了NULL

【问题讨论】:

  • gzip你必须解压。
  • 注:Content-Encoding: gzip。你有 json,它只是 gzip 压缩的。
  • $target_url = "http://examples.com/send";] 我想一定是$target_url = "http://examples.com/send"; 可能是错字?
  • 或删除'Accept-Encoding: gzip, deflate'

标签: php json post


【解决方案1】:

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

Content-encoding: gzip

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

echo gzdecode($content);

【讨论】:

【解决方案2】:

解压内容:

echo gzdecode($contents);

【讨论】:

    【解决方案3】:

    您正在收到标题 Content-Encoding: gzip 所指向的压缩字符串。

    你可以使用php或者js解压。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 2010-11-24
      • 1970-01-01
      • 2013-08-26
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      • 2017-09-27
      相关资源
      最近更新 更多