& quot;应用程序/json& quot;的类型防止发布post变量 [英] Type of "application/json" prevents post variables from being sent
问题描述
我发现,如果尝试使用PHP POST curl,postvars会很好地发送.一旦我添加了内容类型的httpheader: application/json
,postvars就不会再出现了.我已经尝试过将postvars作为JSON字符串和查询字符串.
I've found that if I try a PHP POST curl, the postvars are sent fine. Once I add the httpheader of content-type: application/json
the postvars don't go across any more. I've tried the postvars as a JSON string and as a query string.
显示一些代码:
$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);
推荐答案
一个真正的HTTP帖子,被PHP自动分解成一个数组,必须格式化为name = value对,在PHP中做到这一点的最佳方法是使用http_build_query函数.
A real HTTP Post, that gets broken into an array automagically by PHP must be formatted in name=value pairs, the best way to do this in PHP is using the http_build_query function.
http://ca2.php.net/manual/en/function.http-build-query.php
PHP手册中有一个使用curl的示例:
There is an example that works in the PHP Manual using curl:
http://ca2.php.net/manual/en/function.curl-exec.php#98628
您正在做的是"RAW"帖子,请参见另一个问题:
What you're doing is a 'RAW' post, see this other question:
快速获取RAW Json数据的代码段.
A quick snippet to get the RAW Json data.
<?php
print_r(json_decode(file_get_contents('php://input')));
这篇关于& quot;应用程序/json& quot;的类型防止发布post变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!