PHP通过curl发送POST请求 [英] PHP sending POST request via curl

查看:220
本文介绍了PHP通过curl发送POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆