日常開發中,用習慣了 guzzlehttp/guzzle 包,不得不說是真的好用,推薦大家使用。
命令:composer require guzzlehttp/guzzle 連結
然而最近在專案中卻驚訝的發現,guzzle包是3.*版本,用起來不是很友好。只能自己簡單的寫一下post,get了。
附程式碼:
<?php
namespace App\Service;
class CurlService
{
/**
* Post json 資料
*
* @param $url | url地址
* @param $postData | array
* @param $timeout | int
* @return mixed
*/
public static function postJson($url, $postData, $timeout = 10) {
$jsonStr = json_encode($postData, JSON_UNESCAPED_UNICODE);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonStr),
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return json_decode($data, true);
}
/**
* Get Url 資料
* @param $url
* @return bool|string
*/
public static function get($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結