curl發送json格式數據


  php的curl方法詳細的見官方手冊。

  curl_setopt用法:  http://www.php.net/manual/en/function.curl-setopt.php

  

<?php

$params = array(
    'par1' => 'a',
    'par2' => 11,
);
$header = array("Content-type: application/json");// 注意header頭,格式k:v
$arrParams = json_encode($params);

$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arrParams);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);// curl函數執行的超時時間(包括連接到返回結束) 秒單位
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);// 連接上的時長 秒單位
curl_setopt($ch, CURLOPT_URL, $url);
$ret = curl_exec($ch);

$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);// 對方服務器返回http code
curl_close($ch);

// deal $ret

 

值得注意的是,json_encode()

在處理中文問題上,可以控制是否轉為unicode格式,常量JSON_UNESCAPED_UNICODE這個控制。詳情見http://php.net/manual/zh/function.json-encode.php

 

重試的curl方法:

<?php

function callCurl($url, $arrParams, $format, $timeout = 15, $retry = 3){
        $ch = curl_init();
        if('json' === $format){// header
            $arrParams = json_encode($arrParams);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
        }
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $arrParams);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_URL, $url);
        $ret = curl_exec($ch);
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        while($http_status != 200 && $retry--){
            $ret = curl_exec($ch);
            $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        }

        //記錄請求日志
        $arrLog = array(
            'url' => $url,
            'arrParams' => $arrParams,
            'http_status' => $http_status,
            'curl_error' => curl_error($ch),
            'retry' => $retry,
            'result' => $ret,
        );
        // 記錄log

        curl_close($ch);
        $result = json_decode($ret, true);
        return $result;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM