PHP通过curl发送POST请求 [英] PHP sending POST request via curl
问题描述
我需要使用curl向外部http API发出POST请求。当我使用curl命令行调用API时,它返回正确的数据。但是,当从php脚本调用它时,我很难得到正确的数据。
当我从终端使用curl命令时,我得到正确的数据:
curl -i -HAccept:application / json-X POST -dtype_category_id = 4 http://example.com/api/
在我的curl_setopts()中的CURLOPT_POSTFIELDS的正确格式是什么? / p>
我试过以下(失败):
< ;? php
$ data =type_category_id = 4;
$ ch = curl_init('http://example.com/api/');
curl_setopt($ ch,CURLOPT_CUSTOMREQUEST,POST);
curl_setopt($ ch,CURLOPT_POSTFIELDS,$ data);
curl_setopt($ ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ ch,CURLOPT_HTTPHEADER,array(
'Content-Type:application / json',
'Content-Length:'。strlen($ data))
);
$ result = curl_exec($ ch);
?>
设为 / json
而不是 Content-Type:application / json
在命令行中,但不在php脚本中。
I need to make a POST request to an external http API using curl. When I call the API using the curl command line, it returns the correct data. However, I'm struggling to get the right data when calling it from a php script.
When I use the curl command from the terminal, I get the correct data:
curl -i -H "Accept: application/json" -X POST -d "type_category_id=4" http://example.com/api/
What is the correct format for the CURLOPT_POSTFIELDS in my curl_setopts() in php?
I tried the following (and failed):
<?php
$data = "type_category_id=4";
$ch = curl_init('http://example.com/api/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
$result = curl_exec($ch);
?>
Make it Accept: application/json
instead of Content-Type: application/json
You have done that in the command line but not in the php script.
这篇关于PHP通过curl发送POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!