php - cURL post 请求方法
问题描述
您好,我的 cURL 发布请求方法有问题。我需要从其他主机获取内容,所以我从http://php.net/manual/de/book.curl.php获取了这个方法,因为我知道目标主机也使用 cURL 并向执行可执行文件(exe)的服务。
function postRequest($url, $data, $refer = "", $timeout = 10, $header = [])
{
$curlObj = curl_init();
$ssl = stripos($url,'https://') === 0 ? true : false;
$options = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_AUTOREFERER => 1,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)',
CURLOPT_TIMEOUT => $timeout,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0,
CURLOPT_HTTPHEADER => ['Expect:'],
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
CURLOPT_REFERER => $refer
];
if (!empty($header)) {
$options[CURLOPT_HTTPHEADER] = $header;
}
if ($refer) {
$options[CURLOPT_REFERER] = $refer;
}
if ($ssl) {
//support https
$options[CURLOPT_SSL_VERIFYHOST] = false;
$options[CURLOPT_SSL_VERIFYPEER] = false;
}
curl_setopt_array($curlObj, $options);
$returnData = curl_exec($curlObj);
if (curl_errno($curlObj)) {
//error message
$returnData = curl_error($curlObj);
}
curl_close($curlObj);
return $returnData;
}
我这样调用方法:
$command= array();
$command["cmd"] = "D://Workspace/Interne_Entwicklung/Folder1/Folder2/Executable.exe " . "--command " . chr(34) .
"[{'filters': [ {'Z_RG_Generiert':0} ],auth:[{'userid':'gartner'}],'RequestId': 105.1,'Status': 0}]" . chr(34);
echo postRequest("localhost:8080",$command);
它返回一个错误 (“HTTP 错误 411。请求必须被分块或具有内容长度。”)
我已经尝试向选项数组添加一个选项,该选项将 Content-Length 定义为如下CURLOPT_HTTPHEADER
选项:
$command= array();
$command["cmd"] = "D://Workspace/Interne_Entwicklung/PreisigTest2/PreisigTest2/bin/Debug/PreisigTest2.exe " . "--command " . chr(34) .
"[{'filters': [ {'Z_RG_Generiert':0} ],auth:[{'userid':'gartner'}],'RequestId': 105.1,'Status': 0}]" . chr(34);
$header=array();
$header['Content-Length'] = strlen(json_encode($command));
echo postRequest("localhost:8080",json_encode($command),"",10,$header)
所以我的问题是:
- 此消息的原因是什么?
- 我该如何解决它,定义内容长度还是有其他方法?
解决方案
411 代码是指长度要求。所以这里也需要发送 Content-Length 头。
$command= array();
$command["cmd"] = "D://Workspace/Interne_Entwicklung/PreisigTest2/PreisigTest2/bin/Debug/PreisigTest2.exe " . "--command " . chr(34) .
"[{'filters': [ {'Z_RG_Generiert':0} ],auth:[{'userid':'gartner'}],'RequestId': 105.1,'Status': 0}]" . chr(34);
$header = array('Content-Length: ' . strlen(json_encode($command)));
echo postRequest("localhost:8080",json_encode($command),"",10,$header);
推荐阅读
- amazon-cloudformation - 无法执行 lambda 函数。确保您已授予 CloudWatch Logs 执行函数的权限
- java - 我需要keyboard.close(); 使代码工作?
- sequelize.js - 如何不计算 sequelize 中包含的关联
- javascript - TypeError:无法读取未定义的属性“_events”
- sql-server - 在预部署脚本中重命名表后,如何使用 SQLPackage 强制创建表?
- ios - UNUserNotificationCenter 警报仅在前台解锁/应用程序时触发
- laravel - 基于嵌套关系计数的排序模型 - Laravel 8
- c++ - 可变参数模板到数组访问的无递归扩展
- javascript - 添加边框后如何使文本不移动
- javascript - 在 MVC 架构中,用户的请求是从“控制器”开始还是从“视图”开始?