php 构建http请求,封装 PHP curl http 请求 (全) Composer 安装 httpbuilder,支持 GET,POST,PUT,DELETE...

composer 安装:composer require ethansmart/httpbuilder

github 地址:https://github.com/roancsu/httpbuilder

在PHP 框架中可以使用 guzzlehttp 来构建HTTP Request 服务,但是guzzle 太重了,用起来比较繁琐,所以我用curl封装了PHP HTTP Request Client,支持 GET,POST,PUT,DELETE 方法,并且对文件上传有安全检测功能等等,使用也非常简单,效率高。

Usage:

构建 HttpClient

protected $client ;

function __construct()

{

$this->client = HttpClientBuilder::create()->build();

}

GET Request

$data = [

'uri'=>'https://www.baidu.com'

];

return $this->client

->setHeaders('Content-Type:application/json')

->setHeaders('X-HTTP-Method-Override:GET')

->setHeaders('Request_id: Ethan')

->setTimeout(10)

->Get($data);

POST Request

$data = [

'uri'=>'https://www.baidu.com',

'params'=> [

'user'=>ethan

]

];

return $this->client

->setHeaders('Content-Type:application/json')

->Post($data);

PUT 、DELETE Request

$data = [

'uri'=>'https://www.baidu.com',

'params'=> [

'user'=>ethan

]

];

return $this->client

->setHeaders('Content-Type:application/json')

->Put($data); // Delete($data)

扩展

文件上传

Http/Client.php

但post 数据 大于1k时,设置Expect ;

namespace App\Services\Tools\HttpClient\Http;

use Log;

/**

* Class HttpClient

* @package Ethansmart\HttpBuilder\Http

* Support Http Method : GET, POST, PUT , DELETE

*/

class Client

{

private $ch ;

private $url ;

private $method ;

private $params ;

private $timeout;

protected $multipart ;

public function __construct()

{

$this->timeout = 120 ;

}

public function Get($data)

{

$data['method'] = "GET";

return $this->performRequest($data);

}

public function Post($data)

{

$data['method'] = "POST";

return $this->performRequest($data);

}

public function Put($data)

{

$data['method'] = "PUT";

return $this->performRequest($data);

}

public function Delete($data)

{

$data['method'] = "DELETE";

return $this->performRequest($data);

}

public function Upload($data)

{

$data['method'] = "POST";

$this->multipart = true;

return $this->performRequest($data);

}

/**

* Http 请求

* @param $data

* @return array

*/

public function performRequest($data)

{

$this->ch = curl_init();

$url = $data['url'];

try {

$this->dataValication($data);

} catch (\Exception $e) {

return ['code'=>-1, 'msg'=>$e->getMessage()];

}

$timeout = isset($data['timeout'])?$data['timeout']:$this->timeout;

$headers = $this->setHeaders($data);

curl_setopt($this->ch, CURLOPT_TIMEOUT, $timeout);

curl_setopt($this->ch, CURLOPT_HEADER, true);

curl_setopt($this->ch, CURLINFO_HEADER_OUT, true);

if (!empty($headers)) {

curl_setopt($this->ch, CURLOPT_HTTPHEADER, $headers);

}

curl_setopt($this->ch, CURLOPT_NOBODY, false);

curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, $this->timeout);

curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $this->method); //设置请求方式

if ($this->method=="GET") {

if(strpos($this->url,'?')){

$this->url .= http_build_query($this->params);

}else{

$this->url .= '?' . http_build_query($this->params);

}

}else{

curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->multipart?$this->params:http_build_query($this->params));

}

curl_setopt($this->ch, CURLOPT_URL, $this->url);

if (1 == strpos('$'.$this->url, "https://")) {

curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, false);

}

$result = curl_exec($this->ch);

// if (curl_getinfo($this->ch, CURLINFO_HTTP_CODE) == '200') {}

if(!curl_errno($this->ch)){

list($response_header, $response_body) = explode("\r\n\r\n", $result, 2);

Log::info("Request Headers: ". json_encode($response_header));

Log::info("Request Body :".json_encode($response_body));

$contentType = curl_getinfo($this->ch, CURLINFO_CONTENT_TYPE);

$info = curl_getinfo($this->ch);

Log::info('耗时 ' . $info['total_time'] . ' Seconds 发送请求到 ' . $info['url']);

$response = ['code'=>0, 'msg'=>'OK', 'data'=>$response_body, 'contentType'=>$contentType];

}else{

Log::info('Curl error: ' . curl_error($this->ch)) ;

$response = ['data'=>(object)['code'=>-1, 'msg'=>"请求 $url 出错: Curl error: ". curl_error($this->ch)]];

}

curl_close($this->ch);

return $response;

}

/**

* 设置Header信息

* @param $data

* @return array

*/

public function setHeaders($data)

{

$headers = array();

if (isset($data['headers'])) {

foreach ($data['headers'] as $key=>$item) {

$headers[] = "$key:$item";

}

}

$headers[] = "Expect:"; // post数据大于1k时,默认不需要添加Expect:100-continue

return $headers;

}

public function setTimeout($timeout)

{

if (!empty($timeout) || $timeout != 30) {

$this->timeout = $timeout ;

}

return $this;

}

/**

* 数据验证

* @param $data

* @throws \Exception

*/

public function dataValication($data)

{

if(!isset($data['url']) || empty($data['url'])){

throw new \Exception("HttpClient Error: Uri不能为空", 4422);

}else{

$this->url = $data['url'];

}

if(!isset($data['params']) || empty($data['params'])){

$this->params = [];

}else{

$this->params = $data['params'];

}

if(!isset($data['method']) || empty($data['method'])){

$this->method = "POST";

}else{

$this->method = $data['method'];

}

}

}

本作品采用《CC 协议》,转载必须注明作者和本文链接

Ethan Smart & AI Algorithm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值