我在运行正确的cURL请求时遇到问题。我打算对URL发布一个Post请求。
该示例仅运行命令行cURL请求
$ curl -i -X POST {URL}
问题我正在运行以下代码并且我收到'400 Bad Request'
$ch = curl_init();
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_TIMEOUT, 10 );
$output = curl_exec( $ch );
curl_close( $ch );
任何人都可以帮助正确发送请求。
答案 0 :(得分:2)
您错过了您希望通过请求获得的CURLOPT_POSTFIELDS
。
正如here所解释的那样,您需要设置这些字段:
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3");
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>
答案 1 :(得分:1)
试试这个:
POST功能:
function httpPost($url,$params)
{
$postData = '';
//create name value pairs seperated by &
foreach($params as $k => $v)
{
$postData .= $k . '='.$v.'&';
}
rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
调用函数:
$params = array(
"name" => "Ravishanker Kusuma",
"age" => "32",
"location" => "India"
);
echo httpPost("http://hayageek.com/examples/php/curl-examples/post.php",$params);
看,如果有帮助的话。参考:link
答案 2 :(得分:0)
curl_setopt( $ch, CURLOPT_POST, TRUE );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $array );
检查manual
答案 3 :(得分:0)
要发布,只需使用以下curl选项并尝试。
(if your url is - "https") {
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //if required.
curl_setopt($ch, CURLOPT_URL, );
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
return curl_exec($ch);
我猜你传递的网址没有帖子字段。你可以使用CURLOPT_POSTFIELDS和你的post params他们或者使用http_build_query(post params)将它附加到url http://www.url.com?arg1=val1&arg2=val2
答案 4 :(得分:0)
在花了5个小时的相同代码后,我也找到了解决问题的方法
如果您在发布字段中使用数组,则必须json_encode该数组以识别为POST参数
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($fields));
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($curl);
所以这是带有POST请求的有效CURL代码 如果我的
,请给Rep +