thinkphp5.0 CURL用post请求接口数据

发布时间 2023-11-09 09:43:41作者: 不会代码的小强

//测试 请求接口
public function index(){
$arr = array('a'=>'555','b'=>56454564);
$data=$this->post_json_data('http://www.test.com/public/index/api/postTest',json_encode($arr));
dump(json_decode($data['result'],true));
}

//测试 接口
public function postTest(){
//显示获得的数据
if($this->request->isPost()){
$arr = array('a'=>'666666','b'=>999999);
return json_encode($arr);
}

}
/*
* post 发送JSON 格式数据
* @param $url string URL
* @param $data_string string 请求的具体内容
* @return array
* code 状态码
* result 返回结果
*/
function post_json_data($url, $data_string) {
//初始化
$ch = curl_init();
//设置post方式提交
curl_setopt($ch, CURLOPT_POST, 1);
//设置抓取的url
curl_setopt($ch, CURLOPT_URL, $url);
//设置post数据
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
//设置头文件的信息作为数据流输出
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json; charset=utf-8',
'Content-Length: ' . strlen($data_string))
);
ob_start();
//执行命令
curl_exec($ch);
$return_content = ob_get_contents();
ob_end_clean();
$return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return array('code'=>$return_code, 'result'=>$return_content);
}