is intended to bring easy to follow tutorials and CakePHP code snipets to the CakePHP world. It is in no way affiliated to however offers it support and encouragement where it can.
Our homepage can be found here. > Tutorials > Setting Header Content Type with CakePHP HTTPSocket Flattr this

CakePHP HTTPSocket How to Set Header and Content-Type

Introduction: CakePHP has a built in library you can use to help you make HTTP requests, called HTTPSocket. This is useful for a heap of reasons, including replacing cURL. Why use HTTPSocket instead of cURL? For one, it often makes for tidier code and second, why not? It's built into CakePHP, why not make the most of it.

This page covers how to set headers using CakePHP's HTTPSocket so that you can specify header pairs, content-type, and so forth.<

Assumptions: I'm assuming your using cakePHP 2.* and that you have read the documentation on the CakePHP website, compiled a HTTPSocket request in CakPHP and just want add header information to the request, like you

Example 1. HTTPSocket XML Post Request with Post Fields

In this exaple, we are going to send XML data to an address via HTTPSocket. No headers yet.


App::uses('HttpSocket', 'Network/Http'); // This should be at the top of your Controller $post_data_xml = <some data formatted as XML> $HttpSocket = new HttpSocket(); $results = $HttpSocket->post(', $post_data_xml);

The $post_data_xml string could be created by converting an array to XML in CakePHP using Xml::build.

Example 2: Adding Content-Type with Header

Lets say you are using HttpSocket to communicate with a third party API, like you would with cURL. Chances are, if you are sending the data in XML format as we are in this example you will get an error back from the other send with something like ...

Http Status Error Code 415 Cannot Consume Content Type

This is because you have not specified a Content Type, which you do via the HTTP request header. Here is how we add the content type to the header in CakePHP...


$post_data_xml = <some data formatted as XML> $options = array( 'header' => array( 'Accept' => 'application/xml', 'Content-Type' => 'application/xml; charset=UTF-8' ) ); $HttpSocket = new HttpSocket(); $results = $HttpSocket->post(', $post_data_xml, $options);

Example 3: Converting Array to XML in CakePHP

Slightly unrelated, but if you want to know how we convert an array to XML in CakePHP, we use the Xml Helper. There is a method called build. Here is how we did it for the example on this page.


App::Import('Helper', 'Xml'); // This should be at the top of your Controller $post_data = array('example' => array('another' => 'value') ); try{ $post_data_xml = Xml::build($post_data, array('format' => 'tags')); }catch (XmlException $e) { throw new InternalErrorException(); } $post_data_xml = $post_data_xml->asXML();

Flattr this

Need a CakePHP developer? Or website design services? Hire us, we wrote this tutorial.