【对象】tf_restful_client使用教程

发表于 2020-04-30 10:39:39
阅读 44

介绍

介绍

对象 tf_restful_client 是用来操作 RESTFul 风格接口的客户端

对象 tf_restful_client 自带编码转换,得到的结果数据就是本地编码

对象 tf_restful_client 支持HTTP Basic和OAuth2验证方式,可以自动完成验证操作

定义

导入

tf_restful_client 对象在 common.common_restful 位置

linking('common.common_restful')

属性

debug

修饰:public

说明:用于开启调试模式,一般情况下设置为 3 即可

方法

__construct($pageObj, $opts=null)

参数:

  • $pageObj:page_info 对象实例

  • $opts = null选项参数

getLastStatusCode()

介绍

获取最近一次请求的HTTP状态码

getLastStatusMsg()

介绍

获取最近一次请求的HTTP状态信息

setHTTPAuthBasic($user, $pwd)

介绍

设置HTTP Basic方式的认证参数

参数:

  • $user:认证用户名

  • $pwd:认证密码

setHTTPAuthDigest()

介绍

设置HTTP Digest方式的认证参数

disableHTTPAuth()

介绍

关闭HTTP认证

doAction($url, $method, $myPostData, $myPostHeader, $dataFormatInput, $dataEncodingInput)

介绍

请求远程RESTFul地址

参数:

  • $url接口请求地址

  • $method = null接口请求方式(GET/POST/PUT/DELETE),默认 GET

  • $myPostData = nullPOST数据,只在POST情况下有效

  • $myPostHeader = nullHTTP头信息数据

  • $dataFormatInput = null输入数据格式(json/xml),默认 json

  • $dataEncodingInput = null输入数据编码格式,默认 UTF-8

__getLastRequest()

介绍

获取最近一次请求的请求信息

__getLastResponse()

介绍

获取最近一次请求的响应信息

__setTimeout($secs)

介绍

设置超时时间

参数:

  • $secs:超时时间的秒数

使用

示例

添加用户

完成对接口 http://tongfu.net/api/user 的插入数据操作

$myRestfulObj = new tf_restful_client($this->pageObj);
$myRestfulObj->debug = 3;
$result = $myRestfulObj->doAction("http://tongfu.net/api/user", "POST", array(
    'name'=>"张三",
    'pwd'=>"123456",
));

查询用户

我们通过接口对刚刚写入的用户进行查询

$myRestfulObj = new tf_restful_client($this->pageObj);
$myRestfulObj->debug = 3;
$result = $myRestfulObj->doAction("http://tongfu.net/api/user", "GET");

HTTP Basic认证

我们通过客户端对象完成带HTTP Basic认证的请求

$myRestfulObj = new tf_restful_client($this->pageObj);
$myRestfulObj->debug = 3;
$myRestfulObj->setHTTPAuthBasic("admin","123456");
$result = $myRestfulObj->doAction("http://tongfu.net/api/user", "GET");

注意事项

  • 我们主观认为服务器端返回的数据一定是 UTF-8 编码格式的,除非有提供 Content-Type: application/json; charset=xxx 特别说明

  • 无论服务器端返回的是何种编码,在请求结束后都会根据 PHP_CHARSET 设定转换为本地编码格式

  • 我们主观认为服务器端接收的数据一定是 UTF-8 编码格式的,除非通过 $dataEncodingInput 参数特别指定

tongfuapi

日志
24
浏览
0

相关日志