ws-http 最简单轻量的Curl工具库

最简单轻量的HTTP 客户端库(An Simplified, lightweight HTTP client library)

ws-http
ws-http

可用于 HTTP API 测试,支持 ssl,basic auth,代理,自定义请求头,以及常用HTTP 请求方法.(An HTTP API testing framework, written in PHP using curl. Supports ssl, basic auth, passing custom request headers, and most HTTP request methods.

https://github.com/toohamster/ws-http

需求(Requirements)

安装(Installation)

使用 (Using) Composer

composer.json文件中新增如下行(To install ws-http with Composer, just add the following to your composer.json file):

{
    "require": {
        "toohamster/ws-http": "*"
    }
}

或者手动运行命令(or by running the following command):

php composer require toohamster/ws-http

Http Request 使用(Http Request Usage)

创建一个请求(Creating a Request)

$httpRequest = \Ws\Http\Request::create();

支持的方法(Support Method)

// set config
$httpRequest->jsonOpts($assoc = false, $depth = 512, $options = 0);
$httpRequest->verifyPeer($enabled);
$httpRequest->verifyHost($enabled);
$httpRequest->verifyFile($file);
$httpRequest->getVerifyFile();
$httpRequest->timeout($seconds);
$httpRequest->defaultHeaders($headers);
$httpRequest->defaultHeader($name, $value);
$httpRequest->clearDefaultHeaders();
$httpRequest->curlOpts($options);
$httpRequest->curlOpt($name, $value);
$httpRequest->clearCurlOpts();
$httpRequest->cookie($cookie);
$httpRequest->cookieFile($cookieFile);
$httpRequest->auth($username = '', $password = '', $method = CURLAUTH_BASIC);
$httpRequest->proxy($address, $port = 1080, $type = CURLPROXY_HTTP, $tunnel = false);
$httpRequest->proxyAuth($username = '', $password = '', $method = CURLAUTH_BASIC);

// http call
$httpRequest->get($url, $headers = [], $parameters = null);
$httpRequest->head($url, $headers = [], $parameters = null);
$httpRequest->options($url, $headers = [], $parameters = null);
$httpRequest->connect($url, $headers = [], $parameters = null);
$httpRequest->post($url, $headers = [], $body = null);
$httpRequest->delete($url, $headers = [], $body = null);
$httpRequest->put($url, $headers = [], $body = null);
$httpRequest->patch($url, $headers = [], $body = null);
$httpRequest->trace($url, $headers = [], $body = null);

此处给出一些简单的实例(Let's look at a working example):

$headers = array('Accept' => 'application/json');
$query = array('foo' => 'hello', 'bar' => 'world');

$response = $httpRequest->post('http://mockbin.com/request', $headers, $query);

$response->code;        // 请求响应码(HTTP Status code)
$response->curl_info;   // curl信息(HTTP Curl info)
$response->headers;     // 响应头(Headers)
$response->body;        // 处理后的响应消息体(Parsed body)
$response->raw_body;    // 原始响应消息体(Unparsed body)

JSON 请求(Requests) (application/json)

$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Ws\Http\Request\Body::json($data);

$response = $httpRequest->post('http://mockbin.com/request', $headers, $body);

注意(Notes):

  • Content-Type 会自动设置成(headers will be automatically set to) application/json

表单请求(Form Requests) (application/x-www-form-urlencoded)

$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Ws\Http\Request\Body::form($data);

$response = $httpRequest->post('http://mockbin.com/request', $headers, $body);

注意(Notes):

  • Content-Type 会自动设置成(headers will be automatically set to) application/x-www-form-urlencoded

Multipart Requests (multipart/form-data)

$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');

$body = Ws\Http\Request\Body::multipart($data);

$response = $httpRequest->post('http://mockbin.com/request', $headers, $body);

注意(Notes):

  • Content-Type 会自动设置成(headers will be automatically set to) multipart/form-data.

文件上传(Multipart File Upload)

$headers = array('Accept' => 'application/json');
$data = array('name' => 'ahmad', 'company' => 'mashape');
$files = array('bio' => '/path/to/bio.txt', 'avatar' => '/path/to/avatar.jpg');

$body = Ws\Http\Request\Body::multipart($data, $files);

$response = $httpRequest->post('http://mockbin.com/request', $headers, $body);
$headers = array('Accept' => 'application/json');
$body = array(
    'name' => 'ahmad', 
    'company' => 'mashape'
    'bio' => Ws\Http\Request\Body::file('/path/to/bio.txt', 'text/plain'),
    'avatar' => Ws\Http\Request\Body::file('/path/to/my_avatar.jpg', 'text/plain', 'avatar.jpg')
);

$response = $httpRequest->post('http://mockbin.com/request', $headers, $body);

自定义消息体(Custom Body)

可以使用Ws\Http\Request\Body类提供的方法来生成消息体或使用PHP自带的序列化函数来生成消息体(Sending a custom body such rather than using the Ws\Http\Request\Body helpers is also possible, for example, using a serialize body string with a custom Content-Type):

$headers = array('Accept' => 'application/json', 'Content-Type' => 'application/x-php-serialized');
$body = serialize((array('foo' => 'hello', 'bar' => 'world'));

$response = $httpRequest->post('http://mockbin.com/request', $headers, $body);

授权校验(Authentication)

$httpRequest->auth($username, $password, $method);// default is CURLAUTH_BASIC

支持的方法(Supported Methods)

Method Description
CURLAUTH_BASIC HTTP Basic authentication.
CURLAUTH_DIGEST HTTP Digest authentication. as defined in RFC 2617
CURLAUTH_DIGEST_IE HTTP Digest authentication with an IE flavor. The IE flavor is simply that libcurl will use a special "quirk" that IE is known to have used before version 7 and that some servers require the client to use.
CURLAUTH_NEGOTIATE HTTP Negotiate (SPNEGO) authentication. as defined in RFC 4559
CURLAUTH_NTLM HTTP NTLM authentication. A proprietary protocol invented and used by Microsoft.
CURLAUTH_NTLM_WB NTLM delegating to winbind helper. Authentication is performed by a separate binary application. see libcurl docs for more info
CURLAUTH_ANY This is a convenience macro that sets all bits and thus makes libcurl pick any it finds suitable. libcurl will automatically select the one it finds most secure.
CURLAUTH_ANYSAFE This is a convenience macro that sets all bits except Basic and thus makes libcurl pick any it finds suitable. libcurl will automatically select the one it finds most secure.
CURLAUTH_ONLY This is a meta symbol. OR this value together with a single specific auth value to force libcurl to probe for un-restricted auth and if not, only that single auth algorithm is acceptable.
// custom auth method
$httpRequest->proxyAuth('username', 'password', CURLAUTH_DIGEST);

Cookies

$httpRequest->cookie($cookie)
$httpRequest->cookieFile($cookieFile)

$cookieFile 参数必须是可读取的文件路径(must be a correct path with write permission).

请求对象(Request Object)

$httpRequest->get($url, $headers = array(), $parameters = null)
$httpRequest->post($url, $headers = array(), $body = null)
$httpRequest->put($url, $headers = array(), $body = null)
$httpRequest->patch($url, $headers = array(), $body = null)
$httpRequest->delete($url, $headers = array(), $body = null)
  • url - 请求地址(Endpoint, address, or uri to be acted upon and requested information from)
  • headers - 请求头(Request Headers as associative array or object)
  • body - 请求消息体(Request Body as associative array or object)

可以使用标准的HTTP方法,也可以使用自定义的HTTP方法(You can send a request with any standard or custom HTTP Method):

$httpRequest->send(Ws\Http\Method::LINK, $url, $headers = array(), $body);

$httpRequest->send('CHECKOUT', $url, $headers = array(), $body);

响应对象(Response Object)

  • code - 请求响应码(HTTP Status code)
  • curl_info - HTTP curl信息(HTTP Curl info)
  • headers - 响应头(HTTP Response Headers)
  • body - 处理后的响应消息体(Parsed body)
  • raw_body - 原始响应消息体(Unparsed body)

高级设置(Advanced Configuration)

自定义json_decode选项(Custom JSON Decode Flags)

$httpRequest->jsonOpts(true, 512, JSON_NUMERIC_CHECK & JSON_FORCE_OBJECT & JSON_UNESCAPED_SLASHES);

超时设置(Timeout)

$httpRequest->timeout(5); // 5s timeout

代理(Proxy)

可以设置代理类型(you can also set the proxy type to be one of) CURLPROXY_HTTP, CURLPROXY_HTTP_1_0, CURLPROXY_SOCKS4, CURLPROXY_SOCKS5, CURLPROXY_SOCKS4A, and CURLPROXY_SOCKS5_HOSTNAME.

check the cURL docs for more info.

// quick setup with default port: 1080
$httpRequest->proxy('10.10.10.1');

// custom port and proxy type
$httpRequest->proxy('10.10.10.1', 8080, CURLPROXY_HTTP);

// enable tunneling
$httpRequest->proxy('10.10.10.1', 8080, CURLPROXY_HTTP, true);
代理授权验证 (Proxy Authenticaton)
// basic auth
$httpRequest->proxyAuth('username', 'password', CURLAUTH_DIGEST);

缺省请求头 (Default Request Headers)

$httpRequest->defaultHeader('Header1', 'Value1');
$httpRequest->defaultHeader('Header2', 'Value2');

批量配置(You can set default headers in bulk by passing an array):

$httpRequest->defaultHeaders(array(
    'Header1' => 'Value1',
    'Header2' => 'Value2'
));

清除配置(You can clear the default headers anytime with):

$httpRequest->clearDefaultHeaders();

缺省Curl选项 (Default cURL Options)

You can set default cURL options that will be sent on every request:

$httpRequest->curlOpt(CURLOPT_COOKIE, 'foo=bar');

批量配置(You can set options bulk by passing an array):

$httpRequest->curlOpts(array(
    CURLOPT_COOKIE => 'foo=bar'
));

清除配置(You can clear the default options anytime with):

$httpRequest->clearCurlOpts();

SSL validation

$httpRequest->verifyPeer(false); // Disables SSL cert validation

By default is true.

Http Watcher 使用(Http Watcher Usage)

支持的方法(Support Method)

$watcher = \Ws\Http\Watcher::create($httpResponse);

$watcher->assertStatusCode($assertedStatusCode);
$watcher->assertTotalTimeLessThan($assertedTime);
$watcher->assertHeadersExist(array $assertedHeaders = []);
$watcher->assertHeaders(array $assertedHeaders = []);
$watcher->assertBody($assertedBody, $useRegularExpression = false);
$watcher->assertBodyJson($asserted, $onNotEqualVarExport = false);
$watcher->assertBodyJsonFile($assertedJsonFile, $onNotEqualPrintJson = false);
例子(Examples)
$httpRequest = \Ws\Http\Request::create();

$httpResponse = $httpRequest->get("https://api.github.com");
$watcher = \Ws\Http\Watcher::create($httpResponse);

$watcher
         ->assertStatusCode(200)
         ->assertHeadersExist(array(
            "X-GitHub-Request-Id",
            "ETag"
         ))
         ->assertHeaders(array(
            "Server" => "GitHub.com"
         ))
         ->assertBody('IS_VALID_JSON')
         ->assertTotalTimeLessThan(2);
$httpRequest = \Ws\Http\Request::create();
$httpResponse = $httpRequest->get("https://freegeoip.net/json/8.8.8.8");
$watcher = \Ws\Http\Watcher::create($httpResponse);

$watcher
         ->assertStatusCode(200)
         ->assertHeadersExist(array(
            "Content-Length"
         ))
         ->assertHeaders(array(
            "Access-Control-Allow-Origin" => "*"
         ))
         ->assertBodyJsonFile(dirname(__DIR__) . "/tests/Ws/Http/_json/freegeoip.net.json");

查看所有例子(See the full examples) https://github.com/toohamster/ws-http/blob/master/tests/Ws/Http/ATest.php.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,544评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,430评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,764评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,193评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,216评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,182评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,063评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,917评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,329评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,543评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,722评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,425评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,019评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,671评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,825评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,729评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,614评论 2 353

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,652评论 18 139
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,429评论 2 45
  • 转载自:http://www.cnblogs.com/txw1958/archive/2013/01/19/286...
    php_bruce阅读 2,267评论 1 5
  • =========================================================...
    lavor阅读 3,488评论 0 5
  • “这都不知道?你离抑郁症不远了!”这是本文另外标题,符合互联网气质的。 混迹于互联网多年,在一些“外行”的朋友看来...
    有厘头阅读 238评论 0 0