溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

記一次php curl導(dǎo)致的故障

發(fā)布時(shí)間:2020-07-09 22:07:50 來源:網(wǎng)絡(luò) 閱讀:932 作者:juggles 欄目:開發(fā)技術(shù)

情景描述

本地和alpha環(huán)境curl請(qǐng)求第三方接口正常
beta環(huán)境curl請(qǐng)求失敗

代碼如下

public static function getCurl($url, $type = 'get', $data = '', $decode = true, $header = array())
    {
        $ch = curl_init();    // 初始化CURL句柄
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);//設(shè)置超時(shí)3秒鐘
        curl_setopt($ch, CURLOPT_URL, $url); //設(shè)置請(qǐng)求的URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 設(shè)為TRUE把curl_exec()結(jié)果轉(zhuǎn)化為字串,而不是直接輸出
        if (strtolower($type) == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1); //啟用POST提交
            is_array($data) && $data = http_build_query($data);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //設(shè)置POST提交的字符串
        }
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }

        $document = curl_exec($ch); //執(zhí)行預(yù)定義的CURL
        $info     = curl_getinfo($ch, CURLINFO_HTTP_CODE); //得到返回信息的特性
        curl_close($ch);
        if ($info >= 200 && $info < 300) {
            if ($decode) {
                return json_decode($document, true);
            }
            return $document;
        } else {
            return array("result" => "fail", "cause" => $document);
        }
    }

解決方案

強(qiáng)制使用IPV4請(qǐng)求

curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

curl配置說明:
http://php.net/manual/zh/function.curl-setopt.php

補(bǔ)充

curl 命令行進(jìn)行請(qǐng)求

-4 代表使用IPV4
-d 傳遞數(shù)據(jù),json形式的'{"app_id":"ceshi","secret_key":"123456"}',form形式的"app_id=ceshi&secret_key=123456"
-X POST形式
-H 設(shè)置請(qǐng)求頭

curl -4 url -X POST -H "Content-Type:application/json" -d '{"app_id":"ceshi","secret_key":"123456"}'
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI