Http Client

    • class Client(mixed $config = [])
    • CakePHP includes a basic but powerful HTTP client which can be used formaking requests. It is a great way to communicate with webservices, andremote APIs.

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

    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(...);

    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.

    Warning

    For compatibility reasons, earlier versions of CakePHP will treat stringsbeginning with @ as local or remote file paths. This functionality wasdeprecated in CakePHP 3.0.5 and was removed in a 3.7.

    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. );

    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. json_encode($data),
    5. ['type' => 'json']
    6. );

    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 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 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 create.

    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:

    By setting the ‘type’ key to ‘digest’, you tell the authentication subsystem touse digest 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
    1. // Using the scoped client we created earlier.
    2. $response = $http->get('http://foo.com/test.php');

    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:

    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'));

    New in version 3.5.0: addCookie() was added in 3.5.0

    Response Objects

    • class Cake\Http\Client\Response
    • Response objects have a number of methods for inspecting the response data.

    Changed in version 3.3.0: As of 3.3.0 implements the PSR-7ResponseInterface.

    You read the entire response body as a string:

    1. // Read the entire response as a string.
    2. $response->getStringBody();
    3.  
    4. // Prior to 3.7.0 use
    5. $response->body();
    6. // or
    7. $response->body;

    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. // Prior to 3.7.0
    7. $xml = $response->xml;
    8.  
    9. // Get some JSON
    10. $http = new Client();
    11. $response = $http->get('http://example.com/test.json');
    12. $json = $response->getJson();
    13.  
    14. // Prior to 3.7.0
    15. $json = $response->json;

    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();
    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. $response->getCookieData('session_id');

    Checking the Status Code

    Response objects provide a few methods for checking status codes: