|
1 | | -# http |
| 1 | +## http |
2 | 2 | Http request for php |
| 3 | + |
| 4 | +### Requirement |
| 5 | + |
| 6 | +1. PHP >= 5.6 |
| 7 | +2. **[Composer](https://getcomposer.org/)** |
| 8 | + |
| 9 | +## Installation |
| 10 | + |
| 11 | +```shell |
| 12 | +$ composer require openset/http |
| 13 | +``` |
| 14 | + |
| 15 | +### Usage |
| 16 | + |
| 17 | +```php |
| 18 | +<?php |
| 19 | + |
| 20 | +use Openset\HttpClient; |
| 21 | + |
| 22 | +// 修改默认配置(可选) |
| 23 | +HttpClient::setConfig(['debug' => false, 'verify' => true]); |
| 24 | + |
| 25 | +// 发送get请求 |
| 26 | +$resp = HttpClient::get('https://www.example.com/'); |
| 27 | + |
| 28 | +// Response对象实现了一个PSR-7接口 Psr\Http\Message\ResponseInterface , 包含了很多有用的信息。 |
| 29 | + |
| 30 | +// 你可以获取这个响应的状态码和和原因短语(reason phrase): |
| 31 | + |
| 32 | +$code = $resp->getStatusCode(); // 200 |
| 33 | +$reason = $resp->getReasonPhrase(); // OK |
| 34 | +// 你可以从响应获取头信息(header): |
| 35 | + |
| 36 | +// Check if a header exists. |
| 37 | +if ($response->hasHeader('Content-Length')) { |
| 38 | + echo "It exists"; |
| 39 | +} |
| 40 | + |
| 41 | +// Get a header from the response. |
| 42 | +echo $response->getHeader('Content-Length'); |
| 43 | + |
| 44 | +// Get all of the response headers. |
| 45 | +foreach ($response->getHeaders() as $name => $values) { |
| 46 | + echo $name . ': ' . implode(', ', $values) . "\r\n"; |
| 47 | +} |
| 48 | +// 使用 getBody 方法可以获取响应的主体部分(body),主体可以当成一个字符串或流对象使用 |
| 49 | + |
| 50 | +$body = $resp->getBody(); |
| 51 | +// Implicitly cast the body to a string and echo it |
| 52 | +echo $body; |
| 53 | +// Explicitly cast the body to a string |
| 54 | +$stringBody = (string) $body; |
| 55 | +// Read 10 bytes from the body |
| 56 | +$tenBytes = $body->read(10); |
| 57 | +// Read the remaining contents of the body as a string |
| 58 | +$remainingBytes = $body->getContents(); |
| 59 | + |
| 60 | +``` |
| 61 | + |
| 62 | +## Contributors |
| 63 | + |
| 64 | +[Your contributions are always welcome!](https://github.com/openset/http/graphs/contributors) |
| 65 | + |
| 66 | +## LICENSE |
| 67 | + |
| 68 | +Released under [MIT](https://github.com/openset/http/blob/master/LICENSE) LICENSE |
0 commit comments