`

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

阅读更多

欢迎大家拍砖  https://github.com/toohamster/ws-http 

 

ws-http

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

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.

需求(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_HTTPCURLPROXY_HTTP_1_0CURLPROXY_SOCKS4,CURLPROXY_SOCKS5CURLPROXY_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.

 

 

1
0
分享到:
评论

相关推荐

    HTTP客户端工具库ws-http.zip

    ws-http:简单轻量的HTTP 客户端工具库。 可用于 HTTP API 测试,支持 ssl,basic auth,代理,自定义请求头,以及常用HTTP 请求方法。 $httpRequest = \Ws\Http\Request::create(); $httpResponse = $...

    WWW-Curl-4.17.tar_curl_www_www-curl_Perl_

    **WWW-Curl-4.17.tar - curl, www-curl 和 Perl 知识点详解** `WWW-Curl-4.17.tar` 是一个压缩包文件,它包含了一个名为 `WWW-Curl` 的模块的第 4.17 版本。这个模块是为 Perl 语言设计的,用于与 `curl` 工具集成...

    java--curl工具,用于生成curl链接,直接在服务器上使用

    Java中的Curl工具主要用于生成curl命令,这在服务器端操作和调试HTTP请求时非常有用。Curl是一个强大的命令行工具,允许用户通过命令行接口发送HTTP请求。在Spring Cloud框架中,尤其是与Feign集成时,Curl工具的...

    php_curl-5.3.13-VC9-x64.zip(php curl模块)

    用来替换WAMP server下的php_curl.dll,解决加载curl报错或无法加载问题。下载解压后,覆盖wamp\bin\php\php5.4.3\ext目录下对应文件,重启apache即可。如果不行请检查: 是否已修改php.ini文件去掉extension=...

    windows下curl工具 curl-7.71.1-win64-mingw

    **Windows下的curl工具:curl-7.71.1-win64-mingw** curl是一个强大的命令行工具,用于在不同的操作系统平台上进行文件传输,包括Windows。它的全名是Client URL Library,支持多种协议,如HTTP、HTTPS、FTP、FTPS...

    curl-master.zip_curl_curl-master_curlconfig-d

    通过阅读和分析`curl-master`中的源代码,你可以学习到如何构建网络请求,如何处理各种网络协议,以及如何设计一个跨平台的命令行工具。这对于提升你的网络编程技能,特别是网络请求和响应的处理,会有很大帮助。

    curl-8.9.1-1-win64-mingw 是一个windows命令行工具,GIT下载速度限速软件

    curl-8.9.1_1-win64-mingw 是一个强大且灵活的命令行工具,主要用于从命令行或脚本中传输数据。该工具支持多种协议,包括HTTP、HTTPS、FTP、FTPS、SFTP、SMTP、IMAP等,广泛应用于开发、测试和系统管理等领域。这个...

    php-curl-class:PHP Curl类使发送HTTP请求和与Web API集成变得容易

    安装要安装PHP Curl类,只需: $ composer require php-curl-class/php-curl-class对于最新的提交版本: $ composer require php-curl-class/php-curl-class @dev要求PHP Curl类可与PHP 5.3、5.4、5.5、5.6、7.0、...

    curl-7.33.0 win64.zip

    如果是 Windows 系统,下载 window 版本(curl-7.33.0-win64-ssl-sspi.zip解压后的curl.exe文件,添加到环境变量中,以便在其他路径中通过cmd窗口使用curl命令): 如果你安装了 git shell,也自带了 curl。

    curl-7.78.0-win64-mingw.zip

    总结,"curl-7.78.0-win64-mingw.zip"提供了一个在Windows 64位系统下方便使用的curl工具,结合MinGW环境,使用户能够便捷地利用curl的强大功能进行网络数据交互,无论是简单的HTTP请求还是复杂的自动化任务,都能...

    cURL(curl-8.4.0-3-windows)

    curl-8.4.0_3-win32-mingw.zip curl-8.4.0_3-win64-mingw.zip curl-8.4.0_3-win64a-mingw.zip

    win10下用vs2019编译好的curl 64位库 版本7.84.0

    curl是一个利用URL语法在命令行下工作的文件传输工具,支持很多种http请求操作,详情可以参考Linux curl命令最全详解_Angel_CG的博客-CSDN博客_curl命令。curl现在在linux与win10都是有内置的,在命令行中可以直接...

    cURL工具库及头文件

    cURL是一个利用URL语法在命令行下工作的文件传输工具,1997年首次发行。它支持文件上传和下载,所以是综合传输工具,但按传统,习惯称cURL为下载工具。cURL还包含了用于程序开发的libcurl。cURL支持的通信协议有FTP...

    使用curl-config配置选项

    curl-config 是一个命令行工具,用于显示关于 curl 和 libcurl 安装的信息。下面是对 curl-config 的详细介绍: curl-config 的使用 curl-config 可以使用多种选项来显示不同的信息。这些选项包括: * `--ca`:...

    WWW-Curl-4.15.tar_curl_www_www-curl_Perl_

    **WWW-Curl-4.15.tar - 关于curl、www-curl 和 Perl 的知识** 在互联网编程中,`curl` 是一个强大的命令行工具,用于传输数据到或从服务器,支持多种协议如HTTP、HTTPS、FTP、FTPS等。`curl` 的存在使得开发者可以...

    curl-7.53.1_spendrhy_curl_aix7.1安装curl_

    `curl-7.53.1`是该工具的一个特定版本,由`spendrhy`发布,适用于AIX 7.1操作系统。在AIX系统上安装`curl`对于系统管理员和开发人员来说非常重要,因为它提供了对网络资源的便捷访问,特别是用于调试和测试URL。 ...

    php下curl用法详解

    在PHP中,cURL库是一个强大的工具,用于执行HTTP和其他协议的请求,它允许开发者模拟浏览器行为,如发送POST请求、处理cookies、设置代理等。本文将深入解析PHP下的cURL用法,以便更好地理解和应用。 1. **初始化...

    curl-7.68.0-win64-mingw.zip

    其在Windows平台上的版本为curl-7.68.0-win64-mingw,这是一个专为Windows 64位系统优化的版本,包含了所有必要的库和可执行文件,使得用户无需编译即可直接使用。 首先,让我们深入了解curl的核心功能。curl的主要...

    curl-7.87.0-win32-mingw

    `curl-7.87.0-win32-mingw` 是一个针对Windows 32位系统的curl软件包,由知名开源项目curl提供。curl是一个命令行工具,用于传输数据到或从各种类型的网络协议,如HTTP、HTTPS、FTP、FTPS等。它在开发者和系统管理员...

    Go-golang版本的curl请求库

    在`go-curl-master`这个压缩包中,可能包含了以下内容: 1. `README.md`:库的介绍、安装指南和使用示例。 2. `src`目录:源代码,可能包括了`request.go`、`response.go`等文件,分别定义了请求和响应的结构体及...

Global site tag (gtag.js) - Google Analytics