curl post请求


 * 创建日期:2017年12月11日 23:00:35
 ****************************************************************/

//print_r(getenv());exit;

$url = 'http://baidu.com/test.html';
$data = [
    'a' => 1,
];
$gzip = false;
$action = 'Test';

var_dump(
    httpPost($url, $data, $gzip, $action)
);

function httpPost($url, $data, $gzip, $action)
{
        $connection_timeout = 3000;
        $timeout = 5000;

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
        curl_setopt($curl, CURLOPT_USERAGENT, 'GeTui PHP/1.0');
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, $connection_timeout);
        curl_setopt($curl, CURLOPT_TIMEOUT_MS, $timeout);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        $header = array("Content-Type:text/html;charset=UTF-8");
        if ($gzip) {
                $data = gzencode($data, 9);
                array_push($header,'Accept-Encoding:gzip');
                array_push($header,'Content-Encoding:gzip');
                curl_setopt($curl, CURLOPT_ENCODING, "gzip");
        }
        if(!is_null($action))
        {
                array_push($header,"Gt-Action:".$action);
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

        $curl_version = curl_version();

        //echo $curl_version['version_number'];exit;

        if ($curl_version['version_number'] >= 462850) {
                curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, $connection_timeout);
                curl_setopt($curl, CURLOPT_NOSIGNAL, 1);
        }

        //通过代理访问接口需要在此处配置代理
        $proxyconf = [
            'host' => '127.0.0.1',
            'port' => 3306,
        ];
        //curl_setopt($curl, CURLOPT_PROXY, $proxyConf['host']);
        //curl_setopt($curl, CURLOPT_PROXYPORT, $proxyConf['port']);

        $result = curl_exec($curl);
		$info = curl_getinfo($curl);
		$code = $info["http_code"];

        if (curl_errno($curl) != 0 && $code != 200) {
            throw new \Exception("request errno: ".curl_errno($curl).",url:".$info["url"]);
        }
        curl_close($curl);

        return $result;
}
此条目发表在 扒拉代码 分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*


*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>