Http Client

  • class Cake\Http\Client(mixed $config = [])

CakePHP includes a PSR-18 compliant HTTP client which can be used formaking requests. It is a great way to communicate with webservices, andremote APIs.

Doing Requests

Doing requests is simple and straight forward. Doing a GET request looks like:

  1. use Cake\Http\Client;
  2.  
  3. $http = new Client();
  4.  
  5. // Simple get
  6. $response = $http->get('http://example.com/test.html');
  7.  
  8. // Simple get with querystring
  9. $response = $http->get('http://example.com/search', ['q' => 'widget']);
  10.  
  11. // Simple get with querystring & additional headers
  12. $response = $http->get('http://example.com/search', ['q' => 'widget'], [
  13. 'headers' => ['X-Requested-With' => 'XMLHttpRequest']
  14. ]);

Doing POST and PUT requests is equally simple:

  1. // Send a POST request with application/x-www-form-urlencoded encoded data
  2. $http = new Client();
  3. $response = $http->post('http://example.com/posts/add', [
  4. 'title' => 'testing',
  5. 'body' => 'content in the post'
  6. ]);
  7.  
  8. // Send a PUT request with application/x-www-form-urlencoded encoded data
  9. $response = $http->put('http://example.com/posts/add', [
  10. 'title' => 'testing',
  11. 'body' => 'content in the post'
  12. ]);
  13.  
  14. // Other methods as well.
  15. $http->delete(...);
  16. $http->head(...);
  17. $http->patch(...);

If you have created a PSR-7 request object you can send it usingsendRequest():

  1. use Cake\Http\Client;
  2. use Cake\Http\Client\Request as ClientRequest;
  3.  
  4. $request = new ClientRequest(
  5. 'http://example.com/search',
  6. ClientRequest::METHOD_GET
  7. );
  8. $client = new Client();
  9. $response = $client->sendRequest($request);

Creating Multipart Requests with Files

You can include files in request bodies by including a filehandle in the array:

  1. $http = new Client();
  2. $response = $http->post('http://example.com/api', [
  3. 'image' => fopen('/path/to/a/file', 'r'),
  4. ]);

The filehandle will be read until its end; it will not be rewound before being read.

Building Multipart Request Bodies by Hand

There may be times when you need to build a request body in a very specific way.In these situations you can often use Cake\Http\Client\FormData to craftthe specific multipart HTTP request you want:

  1. use Cake\Http\Client\FormData;
  2.  
  3. $data = new FormData();
  4.  
  5. // Create an XML part
  6. $xml = $data->newPart('xml', $xmlString);
  7. // Set the content type.
  8. $xml->type('application/xml');
  9. $data->add($xml);
  10.  
  11. // Create a file upload with addFile()
  12. // This will append the file to the form data as well.
  13. $file = $data->addFile('upload', fopen('/some/file.txt', 'r'));
  14. $file->contentId('abc123');
  15. $file->disposition('attachment');
  16.  
  17. // Send the request.
  18. $response = $http->post(
  19. 'http://example.com/api',
  20. (string)$data,
  21. ['headers' => ['Content-Type' => $data->contentType()]]
  22. );

Sending Request Bodies

When dealing with REST API’s you often need to send request bodies that are notform encoded. Http\Client exposes this through the type option:

  1. // Send a JSON request body.
  2. $http = new Client();
  3. $response = $http->post(
  4. 'http://example.com/tasks',
  5. json_encode($data),
  6. ['type' => 'json']
  7. );

The type key can either be a one of ‘json’, ‘xml’ or a full mime type.When using the type option, you should provide the data as a string. If you’redoing a GET request that needs both querystring parameters and a request bodyyou can do the following:

  1. // Send a JSON body in a GET request with query string parameters.
  2. $http = new Client();
  3. $response = $http->get(
  4. 'http://example.com/tasks',
  5. ['q' => 'test', '_content' => json_encode($data)],
  6. ['type' => 'json']
  7. );

Request Method Options

Each HTTP method takes an $options parameter which is used to provideaddition request information. The following keys can be used in $options:

  • headers - Array of additional headers
  • cookie - Array of cookies to use.
  • proxy - Array of proxy information.
  • auth - Array of authentication data, the type key is used to delegate toan authentication strategy. By default Basic auth is used.
  • ssl_verify_peer - defaults to true. Set to false to disable SSL certificationverification (not recommended).
  • ssl_verify_peer_name - defaults to true. Set to false to disablehost name verification when verifying SSL certificates (not recommended).
  • ssl_verify_depth - defaults to 5. Depth to traverse in the CA chain.
  • ssl_verify_host - defaults to true. Validate the SSL certificate against the host name.
  • ssl_cafile - defaults to built in cafile. Overwrite to use custom CA bundles.
  • timeout - Duration to wait before timing out in seconds.
  • type - Send a request body in a custom content type. Requires $data toeither be a string, or the _content option to be set when doing GETrequests.
  • redirect - Number of redirects to follow. Defaults to false.

The options parameter is always the 3rd parameter in each of the HTTP methods.They can also be used when constructing Client to createscoped clients.

Authentication

Cake\Http\Client supports a few different authentication systems. Differentauthentication strategies can be added by developers. Auth strategies are calledbefore the request is sent, and allow headers to be added to the requestcontext.

Using Basic Authentication

An example of basic authentication:

  1. $http = new Client();
  2. $response = $http->get('http://example.com/profile/1', [], [
  3. 'auth' => ['username' => 'mark', 'password' => 'secret']
  4. ]);

By default Cake\Http\Client will use basic authentication if there is no'type' key in the auth option.

Using Digest Authentication

An example of basic authentication:

  1. $http = new Client();
  2. $response = $http->get('http://example.com/profile/1', [], [
  3. 'auth' => [
  4. 'type' => 'digest',
  5. 'username' => 'mark',
  6. 'password' => 'secret',
  7. 'realm' => 'myrealm',
  8. 'nonce' => 'onetimevalue',
  9. 'qop' => 1,
  10. 'opaque' => 'someval'
  11. ]
  12. ]);

By setting the ‘type’ key to ‘digest’, you tell the authentication subsystem touse digest authentication.

OAuth 1 Authentication

Many modern web-services require OAuth authentication to access their API’s.The included OAuth authentication assumes that you already have your consumerkey and consumer secret:

  1. $http = new Client();
  2. $response = $http->get('http://example.com/profile/1', [], [
  3. 'auth' => [
  4. 'type' => 'oauth',
  5. 'consumerKey' => 'bigkey',
  6. 'consumerSecret' => 'secret',
  7. 'token' => '...',
  8. 'tokenSecret' => '...',
  9. 'realm' => 'tickets',
  10. ]
  11. ]);

OAuth 2 Authentication

Because OAuth2 is often a single header, there is not a specializedauthentication adapter. Instead you can create a client with the access token:

  1. $http = new Client([
  2. 'headers' => ['Authorization' => 'Bearer ' . $accessToken]
  3. ]);
  4. $response = $http->get('https://example.com/api/profile/1');

Proxy Authentication

Some proxies require authentication to use them. Generally this authenticationis Basic, but it can be implemented by any authentication adapter. By defaultHttp\Client will assume Basic authentication, unless the type key is set:

  1. $http = new Client();
  2. $response = $http->get('http://example.com/test.php', [], [
  3. 'proxy' => [
  4. 'username' => 'mark',
  5. 'password' => 'testing',
  6. 'proxy' => '127.0.0.1:8080',
  7. ]
  8. ]);

The second proxy parameter must be a string with an IP or a domain withoutprotocol. The username and password information will be passed through therequest headers, while the proxy string will be passed throughstream_context_create().

Creating Scoped Clients

Having to re-type the domain name, authentication and proxy settings can becometedious & error prone. To reduce the chance for mistake and relieve some of thetedium, you can create scoped clients:

  1. // Create a scoped client.
  2. $http = new Client([
  3. 'host' => 'api.example.com',
  4. 'scheme' => 'https',
  5. 'auth' => ['username' => 'mark', 'password' => 'testing']
  6. ]);
  7.  
  8. // Do a request to api.example.com
  9. $response = $http->get('/test.php');

The following information can be used when creating a scoped client:

  • host
  • scheme
  • proxy
  • auth
  • port
  • cookies
  • timeout
  • ssl_verify_peer
  • ssl_verify_depth
  • ssl_verify_host

Any of these options can be overridden by specifying them when doing requests.host, scheme, proxy, port are overridden in the request URL:

  1. // Using the scoped client we created earlier.
  2. $response = $http->get('http://foo.com/test.php');

The above will replace the domain, scheme, and port. However, this request willcontinue using all the other options defined when the scoped client was created.See Request Method Options for more information on the optionssupported.

Setting and Managing Cookies

Http\Client can also accept cookies when making requests. In addition toaccepting cookies, it will also automatically store valid cookies set inresponses. Any response with cookies, will have them stored in the originatinginstance of Http\Client. The cookies stored in a Client instance areautomatically included in future requests to domain + path combinations thatmatch:

  1. $http = new Client([
  2. 'host' => 'cakephp.org'
  3. ]);
  4.  
  5. // Do a request that sets some cookies
  6. $response = $http->get('/');
  7.  
  8. // Cookies from the first request will be included
  9. // by default.
  10. $response2 = $http->get('/changelogs');

You can always override the auto-included cookies by setting them in therequest’s $options parameters:

  1. // Replace a stored cookie with a custom value.
  2. $response = $http->get('/changelogs', [], [
  3. 'cookies' => ['sessionid' => '123abc']
  4. ]);

You can add cookie objects to the client after creating it using the addCookie()method:

  1. use Cake\Http\Cookie\Cookie;
  2.  
  3. $http = new Client([
  4. 'host' => 'cakephp.org'
  5. ]);
  6. $http->addCookie(new Cookie('session', 'abc123'));

Response Objects

  • class Cake\Http\Client\Response

Response objects have a number of methods for inspecting the response data.

Reading Response Bodies

You read the entire response body as a string:

  1. // Read the entire response as a string.
  2. $response->getStringBody();

You can also access the stream object for the response and use its methods:

  1. // Get a Psr\Http\Message\StreamInterface containing the response body
  2. $stream = $response->getBody();
  3.  
  4. // Read a stream 100 bytes at a time.
  5. while (!$stream->eof()) {
  6. echo $stream->read(100);
  7. }

Reading JSON and XML Response Bodies

Since JSON and XML responses are commonly used, response objects provide easy touse accessors to read decoded data. JSON data is decoded into an array, whileXML data is decoded into a SimpleXMLElement tree:

  1. // Get some XML
  2. $http = new Client();
  3. $response = $http->get('http://example.com/test.xml');
  4. $xml = $response->getXml();
  5.  
  6. // Get some JSON
  7. $http = new Client();
  8. $response = $http->get('http://example.com/test.json');
  9. $json = $response->getJson();

The decoded response data is stored in the response object, so accessing itmultiple times has no additional cost.

Accessing Response Headers

You can access headers through a few different methods. Header names are alwaystreated as case-insensitive values when accessing them through methods:

  1. // Get all the headers as an associative array.
  2. $response->getHeaders();
  3.  
  4. // Get a single header as an array.
  5. $response->getHeader('content-type');
  6.  
  7. // Get a header as a string
  8. $response->getHeaderLine('content-type');
  9.  
  10. // Get the response encoding
  11. $response->getEncoding();

You can read cookies with a few different methods depending on how muchdata you need about the cookies:

  1. // Get all cookies (full data)
  2. $response->getCookies();
  3.  
  4. // Get a single cookie's value.
  5. $response->getCookie('session_id');
  6.  
  7. // Get a the complete data for a single cookie
  8. // includes value, expires, path, httponly, secure keys.
  9. $response->getCookieData('session_id');

Checking the Status Code

Response objects provide a few methods for checking status codes:

  1. // Was the response a 20x
  2. $response->isOk();
  3.  
  4. // Was the response a 30x
  5. $response->isRedirect();
  6.  
  7. // Get the status code
  8. $response->getStatusCode();

Changing Transport Adapters

By default Http\Client will prefer using a curl based transport adapter.If the curl extension is not available a stream based adapter will be usedinstead. You can force select a transport adapter using a constructor option:

  1. use Cake\Http\Client\Adapter\Stream;
  2.  
  3. $client = new Client(['adapter' => Stream::class]);