cURL发布请求方法

时间:2018-06-05 06:59:37

标签: php curl php-curl

您好我的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);

然后它返回错误 (" 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)

所以我的问题是:

  • 这条消息的原因是什么?
  • 如何通过定义内容长度或其他方式来解决它?

1 个答案:

答案 0 :(得分:1)

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);