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;
    }
原文地址:https://www.cnblogs.com/firstForEver/p/6130820.html