作者 karlet

feat:修改curl的post方法

... ... @@ -19,15 +19,13 @@ class Curl
$output = curl_exec($ch);
if ($output === false) {
echo 'Curl error: ' . curl_error($ch);
curl_close($ch);
return json_encode(['code' => '-1', 'msg' => 'curl error: ' . curl_error($ch)]);
}
curl_close($ch);
return $output;
}
//post 获取数据
static public function httpPost($url, $param = [], $header = [])
static public function httpPost($url, $param = [], $header = [], $asBody = false)
{
if (empty($url)) {
return false;
... ... @@ -37,21 +35,42 @@ class Curl
$opts = [];
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_USERAGENT] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.98 Safari/537.36";
if (!empty($header) && in_array('Content-Type:application/json', $header)) {
$opts[CURLOPT_POSTFIELDS] = json_encode($param);
// 修改判断逻辑
$isJson = false;
foreach ($header as $h) {
if (stripos($h, 'Content-Type: application/json') !== false) {
$isJson = true;
break;
}
}
if ($asBody) {
// form-data格式提交
$boundary = '----WebKitFormBoundary' . uniqid();
$body = '';
foreach ($param as $key => $value) {
$body .= "--$boundary\r\n";
$body .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n";
$body .= "$value\r\n";
}
$body .= "--$boundary--\r\n";
$opts[CURLOPT_POSTFIELDS] = $body;
$header[] = "Content-Type: multipart/form-data; boundary=$boundary";
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
} else {
$opts[CURLOPT_POSTFIELDS] = http_build_query($param);
$opts[CURLOPT_POSTFIELDS] = $isJson ? json_encode($param) : http_build_query($param);
}
curl_setopt_array($ch, $opts);
$output = curl_exec($ch);
if ($output === false) {
echo 'Curl error: ' . curl_error($ch);
curl_close($ch);
return json_encode(['code' => '-1', 'msg' => 'curl error: ' . curl_error($ch)]);
}
curl_close($ch);
return $output;
}
//delete 请求
static public function httpDelete($url, $param = [], $header = [])
{
... ... @@ -67,9 +86,6 @@ class Curl
$output = curl_exec($ch);
if ($output === false) {
echo 'Curl error: ' . curl_error($ch);
echo 'Curl error: ' . curl_error($ch);
curl_close($ch);
return json_encode(['code' => '-1', 'msg' => 'curl error: ' . curl_error($ch)]);
}
curl_close($ch);
return $output;
... ...