简体   繁体   English

使用Curl发布JSON

[英]Post JSON using Curl

I am receiving a JSON which I can receive using php://input and I need to post it back to a different URL, but I'm not sure how to format it. 我收到了一个JSON,可以使用php:// input接收到,我需要将其发布回另一个URL,但是我不确定如何格式化它。 Here's how I receive it: 这是我收到的方式:

$updates = file_get_contents("php://input"); $ updates = file_get_contents(“ php:// input”);

I could json_decode it and then parse out the array so that it would fit a normal POST-like request such as hello=world&stack=overflow etc. But is it possible to pass the JSON just into a curl post like this: 我可以对其进行json_decode解析,然后解析出该数组,以使其适合常规的类似POST的请求,例如hello = world&stack = overflow等。但是是否可以将JSON传递给curl帖子,如下所示:

curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $updates);

and then the client could just php://input to grab the data again? 然后客户端可以只是php:// input再次获取数据? The reason I ask is because the client says he is not receiving the data, it may be he doesn't have it set up correctly. 我问的原因是因为客户说他没有收到数据,可能是因为他没有正确设置数据。 I've noticed when you do something like this through a command line you have to include -H in the command so that the data is interpretted as normal POST, perhaps there's a libcurl CURLOPT I need to set? 我注意到,当您通过命令行执行此类操作时,必须在命令中包含-H,以便将数据解释为普通的POST,也许我需要设置libcurl CURLOPT?

Thanks! 谢谢!

Well folks, I have figured this one out! 伙计们,我已经弄清楚了这一点!

To send a post as a different content-type (ie.. application/json or text/xml) add this setopt call 要将帖子发送为其他内容类型(例如application / json或text / xml),请添加此setopt调用

curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/json')); curl_setopt($ ch,CURLOPT_HTTPHEADERS,array('Content-Type:application / json'));

You can also use 您也可以使用

curl --silent --request POST --header 'Content-Type: application/json' \
--data $updates \
-k http://URL_to_which_you_want_to_post

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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