【问题标题】:Type of "application/json" prevents post variables from being sent“application/json”的类型阻止发送后变量
【发布时间】:2011-06-28 18:21:43
【问题描述】:

我发现如果我尝试 PHP POST curl,postvars 可以正常发送。一旦我添加了内容类型的httpheader:application/json,postvars 就不会再出现了。我已经尝试将 postvars 作为 JSON 字符串和查询字符串。

显示一些代码:

$ch = curl_init();

$post =  json_encode(array('p1' => 'blahblahblah', 'p2' => json_encode(array(4,5,6))));

$arr = array();
array_push($arr, 'Content-Type: application/json; charset=utf-8');

curl_setopt($ch, CURLOPT_HTTPHEADER, $arr);
curl_setopt($ch, CURLOPT_URL, 'https://example.com/file.php');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

curl_exec($ch);
curl_close($ch);

【问题讨论】:

  • 我在 $post 上运行了 json_encode。这还不够吗,或者请求正文是什么/其他地方?
  • 近乎...我不认为是这样...

标签: php json curl http-headers


【解决方案1】:

一个真正的 HTTP Post,被 PHP 自动分解成一个数组,必须格式化为 name=value 对,在 PHP 中执行此操作的最佳方法是使用 http_build_query 函数。

http://ca2.php.net/manual/en/function.http-build-query.php

PHP 手册中有一个使用 curl 的示例:

http://ca2.php.net/manual/en/function.curl-exec.php#98628

您正在做的是“原始”帖子,请参阅另一个问题:

How to post JSON to PHP with curl

快速获取 RAW Json 数据的 sn-p。

<?php

print_r(json_decode(file_get_contents('php://input')));

【讨论】:

  • 我一开始没有提到,我应该有的(事后看来是 20/20)是我不控制我发布的页面。它实际上也是我发布的一个 .net 工具,很生气他们没有发布信息。使用 jQuery 发布可以很好地模拟我正在做的事情。由于跨域问题,我只是卷曲。当我引入 CURLOPT_HTTPHEADER 时 PHP Curl 中断,我必须指定内容类型或我正在与之交谈的服务器引导我。困惑。
  • POST 变量通过,但是一旦我将内容类型设置为 application/json,它们就会退出。这是怎么回事!?
  • 好吧,不知道 .Net 脚本是如何工作的,很难提供解决方案。 ;) 听起来实际上另一端的脚本是内容类型不是多部分/表单数据。
  • 这很糟糕,因为这在使用 jQuery (XHR) 时有效,但是 curl 不起作用:( 如果我可以让 curl 使用 application/json 的 Content-Type 并发送 POST数据作为 POSTDATA 而不是 RAW DATA,那么我会很高兴。我想这是货架上的一个。太伤心了。感谢您的专业帮助。
  • PHP 将 POST vars 更改为 RAW post,这意味着您需要使用 file_get_contents 或等价的。这是正确的答案(感谢@anuckistani),但由于我正在使用.net 后端,我无法解决这个问题:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
  • 2013-06-28
  • 2015-11-06
  • 2019-09-03
  • 2021-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多