首页 > 解决方案 > 如何正确发送 POSTFIELDS 到 cURL

问题描述

如图所示,我需要通过 cURL 发送 POST 数据。

带有 POST 数据的图像

我有这个代码

 $data = [
            'action' => 'order_cost',
            'address' => 'http://91.211.117.3:720'
        ];

  $query = http_build_query($data);

   $url = "https://ap4.taxi/api/TaxiAPI.php";
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36');
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvJFySHvqeKppEN9W',
            )
        );
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        $output = curl_exec($ch);

        curl_close($ch);

        var_dump($output);

但我得到一个错误

有错误的图像

我已经尝试了很多选择。邮递员正常发送POST,我收到答案。

请告诉我,我什至无法想象如何做到这一点。

标签: phpcurl

解决方案


function execute_curl($url, $curlopt = array()){
    $ch = curl_init();
    $strCookie = session_name().'='.session_id().'; path=/';
    session_write_close();
    $default_curlopt = array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => 0,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_COOKIE => $strCookie,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_USERAGENT => "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.13) Gecko/20101203 AlexaToolbar/alxf-1.54 Firefox/3.6.13 GTB7.1"
    );
    $curlopt = $curlopt + $default_curlopt;

    curl_setopt_array($ch, $curlopt);
    $response = curl_exec($ch);
    $errormsg = curl_error($ch);
        $errorCode = curl_errno($ch);
    $results = array();
    if($errormsg)
    {
        $results['status'] = 'error';
        $results['data'] = $errormsg;
        $results['errorcodetxt'] = curl_error_codes($errorCode);
    }
    else
    {
        $results['status'] = 'success';
        $results['data'] = $response;
    }
    curl_close($ch);
    return $results;
}

$curlopt = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => 1);
$curlresponse = execute_curl($url, $curlopt);   

推荐阅读