weew/http

基本 HTTP 层。

v1.13.0 2016-11-03 17:04 UTC

README

Build Status Code Quality Test Coverage Version Licence

目录

安装

composer require weew/http

响应

基本响应

$response = new HttpResponse();
$response->send();
HTTP/1.1 200 OK
Host: localhost
Connection: close

内容

$response = new HttpResponse();
$response->setContent('<h1>Hello World!</h1>');
$response->send();
HTTP/1.1 200 OK
Host: localhost
Connection: close
content-type: text/html

<h1>Hello World!</h1>

状态码

$response = new HttpResponse(HttpStatusCode::UNAUTHORIZED);
// or
$response = new HttpResponse(401);
$response->send();
HTTP/1.1 401 Unauthorized
Host: localhost
Connection: close

头部

$response = new HttpResponse();
$response->getHeaders()->set('foo', 'bar');
$response->send();
HTTP/1.1 200 OK
Host: localhost
Connection: close
foo: bar

Cookie

$response = new HttpResponse();
$response->getQueuedCookies()->add(new Cookie('foo', 'bar'));
$response->send();
HTTP/1.1 200 OK
Host: localhost
Connection: close
set-cookie: foo=bar; path=/; httpOnly

自定义响应

HtmlResponse

$response = new HtmlResponse();
$response->setHtmlContent('<h1>Hello World!</h1>');
$response->send();
HTTP/1.1 200 OK
Host: localhost
Connection: close
content-type: text/html

<h1>Hello World!</h1>

JsonResponse

$response = new JsonResponse();
$response->getData()->set('Hello', 'World!');
$response->send();
HTTP/1.1 200 OK
Host: localhost
Connection: close
content-type: application/json

{"Hello":"World!"}

BasicAuthResponse

$response = new BasicAuthResponse('Please login');
$response->send();
HTTP/1.1 200 OK
Host: localhost
Connection: close
www-authenticate: basic realm="Please login"

请求

基本请求

构建自定义请求非常简单。

$request = new HttpRequest(
    HttpRequestMethod::POST,
    new Url('http://example.com')
);
$request->setContent('foo=bar');

GET 参数

$request = new HttpRequest();
$request->getUrl()->getQuery()->set('foo', 'bar');

echo $request->getUrl()->getQuery();
// foo=bar

POST 数据

$request = new HttpRequest();
$request->getData()->set('foo', 'bar');
$request->getData()->set('bar', 'foo');

echo $request->getContent();
// foo=bar&bar=foo

头部

你可以像在 HttpResponse 类中一样访问头部信息。

$request = new HttpRequest();
$request->getHeaders()->set('foo', 'bar');
$request->getHeaders()->add('foo', 'foo');

var_dump($request->getHeaders()->get('foo'));
// ['bar', 'foo']
echo $request->getHeaders()->find('foo');
// foo

当前请求

有时,有一个表示当前接收到的 HTTP 请求的对象会很有用。

$request = new CurrentRequest();
var_dump($request->toArray());
// all the data that the server received from the client

基本认证

通过基本认证认证请求非常简单。

$request = new HttpRequest();
$request->getBasicAuth()->setUsername('foo');
$request->getBasicAuth()->setPassword('bar');
echo $request->getBasicAuth()->getToken();
// Zm9vOmJhcg==
echo $request->getHeaders()->find('authentication');
// Basic Zm9vOmJhcg==

相关项目

  • URL:在整个项目中使用。
  • HTTP Client:一个简单的 HTTP 客户端,允许你发送和接收标准化的 HttpRequest 和 HttpResponse 对象。