PHP code example of hehex / hehep-hclient

1. Go to this page and download the library: Download hehex/hehep-hclient library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hehex / hehep-hclient example snippets



$config = [
    //'class'=>'hclient\Client',// 客户端管理器
    // 默认传输器
    'transport'=>'curl',// 目前提供curl,socket,stream 三种传输方式,
    
    // request 对象格式对象
    'formatters'=>[
        'json'=>'json',
        'xml'=>'xml',
        'none'=>'none'
    ],

    // response 对象格式对象
    'parsers'=>[
        'json'=>'json',
        'xml'=>'xml',
        'none'=>'none'
    ],
    // 自定义站点信息
    'sites'=>[
        
        'api'=>[
            // 请求类相关属性
            'class'=>'hclient\base\Request',
            'baseUrl'=>'http://xxxx.xxxx.cn/',// 站点域名或地址
            'method'=>'POST',// http 方法
            'protocol'=>'',// 请求协议,比如http,一般配置socket使用
            'format'=>'json',// 格式化名称
            'options'=>[],// 传输协议参数
            'response'=>[
                // 响应类相关属性
                'class'=>'hclient\extend\ApiResponse',
                'protocol'=>'',// 请求协议,比如http,一般配置socket使用
                'format'=>'json',// 格式化名称
            ],
        ],
        'sina'=>[
            'baseUrl'=>'http://blog.sina.com.cn/',
            'method'=>'GET'
        ],
        'baidu'=>[
            'baseUrl'=>'http://www.thinkphp.cn/',
            'method'=>'GET'
        ]
    ],
];


use hclient\Client;
$hclient = new Client();

// 发送get 请求
$html = $hclient->get("http://www.baidu.com/")->send()->getContent();

// 设置请求参数
$html = $hclient->get("http://www.baidu.com/",['id'=>1])->send()->getContent();

// 简写方式
$html = $hclient->getResult("http://www.baidu.com/",['id'=>1]);

// 发送post 请求
$html = $hclient->post("http://www.baidu.com/",['id'=>1])->send()->getContent();
// 简写方式
$html = $hclient->postResult("http://www.baidu.com/",['id'=>1]);

// 其他请求method
$html = $hclient->xxxResult("http://www.baidu.com/",['id'=>1]);


$config = [
    // 自定义站点信息
    'sites'=>[
        'orderapi'=>[
            // 请求类相关属性
            'class'=>'hclient\base\Request',
            'baseUrl'=>'http://xxxx.xxxx.cn/',// 站点域名或地址
            'method'=>'POST',// http 方法
            'protocol'=>'',// 请求协议,比如http,一般配置socket使用
            'format'=>'',// 格式化名称,json
            'response'=>[
                'class'=>'hclient\extend\ApiResponse',// 定义响应类
                'protocol'=>'',// 请求协议,比如http,一般配置socket使用
                'format'=>'json',// 格式化名称,
                'varCode'=>'code',// 业务状态码字段名称,
                'varMsg'=>'message',// 业务提示信息字段名称,
                'varResult'=>'data',//  业务数据字段名称,
                'succCode'=>200,// 业务状态码成功值,
            ],
        ],
    ],
];


use hclient\Client;
$hclient = new Client();
$response = $hclient->api('orderapi','product/add',['name'=>'商品','price'=>10.2,'stock'=>100]);
$response = $hclient->site('orderapi')->api('product/add',['name'=>'商品','price'=>10.2,'stock'=>100]);
$response = $hclient->orderapi->api('product/add',['name'=>'商品','price'=>10.2,'stock'=>100]);

// 判断请求是否成功,业务状态码是否正确
$response->isOk();

// 自定义状态码
$response->isOk(2000);

// 获取业务提示消息
$response->getMessage();

// 获取业务数据
$response->getResult();

// 获取业务状态码
$response->getErrorCode();


use hclient\Client;
$hclient = new Client();

// 添加站点
$hclient->addSite('sina',[
    'baseUrl'=>'https://sports.sina.com.cn/',
    'method'=>'GET'
]);

$response = $hclient->uri("sina","system/site/siteInit",['id'=>1])->send();
// 获取返回的原始内容
$content = $response->getContent();

// 获取格式化后的内容
$data = $response->setFormat("json")->getData();

// 直接获取格式化后数据
$data = $hclient->uriResult("sina","system/site/siteInit",['id'=>1]);


use hclient\Client;
$hclient = new Client();
$hclient->site('baidu')->get('system/site/siteInit');
$hclient->site('baidu')->post('system/site/siteInit',['id'=>1]);
$hclient->site('baidu')->getResult('system/site/siteInit');
$hclient->site('baidu')->postResult('system/site/siteInit',['id'=>1]);

use hclient\Client;
$hclient = new Client();
$response = $hclient->site('baidu')
    ->uri('system/site/siteInit',['id'=>1])
    ->send();


use hclient\Client;
$hclient = new Client();
$response = $hclient->site()
    ->setBaseUrl('https://sports.sina.com.cn/')
    ->uri('system/site/siteInit',['id'=>1])
    ->send();


use hclient\Client;
$hclient = new Client();

// 方式1
$reqeusts = [
    'reqeust1'=>$hclient->uri("md","system/site/siteInit",['id'=>1]),
    'reqeust2'=>$hclient->uri("md","system/site/siteInit",['id'=>2]),
];

$responses = $hclient->batchSend($reqeusts);
$content = $responses['reqeust1']->getContent();
$content = $responses['reqeust2']->getContent();


// 方式2
$reqeusts = [
    $hclient->uri("md","system/site/siteInit",['id'=>1])->setIndex('reqeust1'),
    $hclient->uri("md","system/site/siteInit",['id'=>2])->setIndex('reqeust2'),
];

$responses = $hclient->batchSend($reqeusts);
$content = $responses['reqeust1']->getContent();
$content = $responses['reqeust2']->getContent();


use hclient\Client;
$hclient = new Client();

$requestGroup = $hclient->batch();
$requestGroup->getResult('http://www.baidu.com')->setIndex("reqeust1");
$requestGroup->getResult('http://www.baidu.com')->setIndex("reqeust2");
$res_result = $requestGroup->send();
$res_result['reqeust1'];
$res_result['reqeust2'];

$requestGroup = $hclient->batch();
$requestGroup->get('http://www.baidu.com')->setIndex("reqeust1");
$requestGroup->getResult('http://www.baidu.com')->setIndex("reqeust2");
$res_result = $requestGroup->send();	
$res_result['reqeust1'];
$res_result['reqeust2'];

// reqeust1 返回的结果是response 对象
$response = $res_result['reqeust1'];
$html = $res_result['reqeust2'];


use hclient\Client;
$hclient = new Client();
$hclient->registerFormat('json','hclient\formatters\JsonFormatter');
$hclient->registerParser('json','hclient\formatters\JsonParser');


use hclient\Client;
$hclient = new Client();
// $request_data json 编码后传输
$request_data = ['id'=>1];
$response = $hclient->post('http://www.baidu.com',$request_data)->setFormat('json')->send();

// 对返回结果json 解码
$data = $response->setFormat('json')->getData();


use hclient\Client;
$hclient = new Client();
$reqeust = $hclient->uri("md","system/site/siteInit",['id'=>1]);
$reqeust->addHeaders([
    'c'=>1,
    'n'=>time(),
]);


use hclient\Client;
$hclient = new Client();
$reqeust = $hclient->uri("md","system/site/siteInit",['id'=>1]);
$reqeust->addCookie([
    "name"=>"ok",// cookie 名称
    'value'=>"12121",// cookie 值
    "expire"=>60 * 30,// cookie 有效期
]);

$reqeust->setCookie("ok","value",60 * 30);


use hclient\Client;
$hclient = new Client();
$reqeust = $hclient->uri("md","system/site/siteInit",['id'=>1]);

// 设置http method
$reqeust->setMethod("post");
$reqeust->setMethod("get");


use hclient\Client;
$hclient = new Client();

$hclient->registerTransport('curl','hclient\transports\CurlTransport');


use hclient\Client;
$hclient = new Client();
$hclient->setTransport('curl');

use hclient\Client;
$hclient = new Client();
$hclient->post('http://www.baidu.com')->setTransport('curl')->send();

use hclient\Client;
$hclient = new Client();
$reqeust = $hclient->uri("md","system/site/siteInit",['id'=>1]);

// 设置传输协议相关参数
$reqeust->setTransportOptions([
    CURLOPT_RETURNTRANSFER=>true,
    CURLOPT_POST=>'POST'
]);



use hclient\Client;
$hclient = new Client();
$reqeust = $hclient->uri("md","system/site/siteInit",['id'=>1]);
$response = $reqeust->send();

// 验证是否错误(验证网络,解析数据,Transport(传输层) 是否有错误)
if ($response->hasError()) {
    echo "error";
} else {
    echo "succeed";
}

// 验证是否网络错误(主要验证header http-code 状态码 是否等于20x)
if ($response->hasNetworkError()) {
    echo "error";
} else {
    echo "succeed";
}

// 获取错误信息
$response->getError();


namespace hclient\formatters;

use hclient\base\Request;

class JsonFormatter implements FormatterInterface
{
    
    // 实现此方法
    public function format(Request $request):void
    {
        $request->getHeaders()->set('Content-Type', 'application/json; charset=UTF-8');
        $request->setContent(json_encode($request->getData()));
    }
}

namespace hclient\formatters;
use hclient\base\Response;

/**
 * Response json 反序列化
 *<B>说明:</B>
 *<pre>
 * 略
 *</pre>
 */
class JsonParser implements ParserInterface
{
    // 实现此方法
    public function parse(Response $response):void
    {
        $response->setData(json_decode((string) $response->getContent(), true));
    }
}

namespace  hclient\transports;
use hclient\base\Request;

class StreamTransport extends Transport
{
    // 实现此方法
    public function send(Request $request)
    {
        // 发送单个请求

        return $request;
    }
    
    // 扩展此方法
    public function batchSend(array $requests)
    {
        // 批量发送多个请求
    }

}