Skip to content

Commit

Permalink
Add post request example
Browse files Browse the repository at this point in the history
  • Loading branch information
g105b committed Feb 21, 2019
1 parent c0f9661 commit 0f5166a
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ $response = $http->sendRequest($fastRequest);
$http->wait();
```

For more extensive examples, check out the code in the [example directory](/example).

[psr-7]: http://www.php-fig.org/psr/psr-7/
[fetch-standard]: https://fetch.spec.whatwg.org/
[fetch-js]: https://developer.mozilla.org/en/docs/Web/API/Fetch_API
Expand Down
47 changes: 47 additions & 0 deletions example/02-post-request.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php
require(implode(DIRECTORY_SEPARATOR, ["..", "vendor", "autoload.php"]));

use Gt\Fetch\Http;
use Gt\Fetch\BodyResponse;

/*
* This example uses postman-echo.com do test the request/response.
* See https://docs.postman-echo.com/ for more information.
*/

// Example: Post form data to the echo server.

$http = new Http();
$http->fetch("https://postman-echo.com/post", [
// All of the request parameters can be passed directly here, or alternatively
// the fetch() function can take a PSR-7 RequestInterface object.
"method" => "POST",
"headers" => [
"Content-Type" => "application/x-www-form-urlencoded",
],
"body" => http_build_query([
"name" => "Mark Zuckerberg",
"dob" => "1984-05-14",
"email" => "[email protected]",
]),
])
->then(function(BodyResponse $response) {
if(!$response->ok) {
echo "Error posting to Postman Echo." . PHP_EOL;
exit;
}
// Postman Echo servers respond with a JSON representation of the request
// that was received.
return $response->json();
})
->then(function($json) {
echo "The Postman Echo server received the following form fields:";
echo PHP_EOL;

foreach($json->form as $key => $value) {
echo "$key = $value" . PHP_EOL;
}
});

// To execute the above Promise(s), call wait() or all().
$http->wait();

0 comments on commit 0f5166a

Please sign in to comment.