cURL post 请求方式

cURL post request method

您好,我的 cURL post 请求方法有问题。我需要从其他主机获取内容,所以我从 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);

它 returns 我 错误 ("HTTP Error 411. The request must be chunked or have a content length.") 我已经尝试向选项数组添加一个选项,该选项数组将 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);