Skip to content

Commit

Permalink
Fix Http client headers when array data is used.
Browse files Browse the repository at this point in the history
When building a client request with constructor arguments, the headers
should be applied before the body is set. This is necessary as setting
the body can change the content-type based on the contents. Arrays are
converted into urlencoded data, which needs to override the
content-type on the request.
  • Loading branch information
markstory committed Jul 12, 2016
1 parent d051712 commit d0dd6de
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Http/Client/Request.php
Expand Up @@ -45,12 +45,12 @@ public function __construct($url = '', $method = self::METHOD_GET, array $header
$this->validateMethod($method);
$this->method = $method;
$this->uri = $this->createUri($url);
$this->body($data);
$headers += [
'Connection' => 'close',
'User-Agent' => 'CakePHP'
];
$this->addHeaders($headers);
$this->body($data);
}

/**
Expand Down
39 changes: 39 additions & 0 deletions tests/TestCase/Network/Http/RequestTest.php
Expand Up @@ -22,6 +22,45 @@
*/
class RequestTest extends TestCase
{
/**
* test string ata, header and constructor
*
* @return void
*/
public function testConstructorStringData()
{
$headers = [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer valid-token',
];
$data = ['a' => 'b', 'c' => 'd'];
$request = new Request('http://example.com', 'POST', $headers, json_encode($data));

$this->assertEquals('http://example.com', $request->url());
$this->assertEquals('POST', $request->getMethod());
$this->assertEquals('application/json', $request->getHeaderLine('Content-Type'));
$this->assertEquals(json_encode($data), $request->body());
}

/**
* test array data, header and constructor
*
* @return void
*/
public function testConstructorArrayData()
{
$headers = [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer valid-token',
];
$data = ['a' => 'b', 'c' => 'd'];
$request = new Request('http://example.com', 'POST', $headers, $data);

$this->assertEquals('http://example.com', $request->url());
$this->assertEquals('POST', $request->getMethod());
$this->assertEquals('application/x-www-form-urlencoded', $request->getHeaderLine('Content-Type'));
$this->assertEquals('a=b&c=d', $request->body());
}

/**
* test url method
Expand Down

0 comments on commit d0dd6de

Please sign in to comment.