PHPackages                             markenwerk/json-http-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. markenwerk/json-http-client

Abandoned → [chroma-x/json-http-client](/?search=chroma-x%2Fjson-http-client)Library[HTTP &amp; Networking](/categories/http)

markenwerk/json-http-client
===========================

A JSON HTTP client library. This project also is the reference implementation for extending the PHP Basic HTTP Client.

4.0.1(1y ago)21.4k1MITPHPPHP ^8.3

Since Apr 28Pushed 1y ago1 watchersCompare

[ Source](https://github.com/chroma-x/php-json-http-client)[ Packagist](https://packagist.org/packages/markenwerk/json-http-client)[ Docs](https://chroma-x.de/)[ RSS](/packages/markenwerk-json-http-client/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (1)Versions (18)Used By (0)

PHP JSON HTTP Client
====================

[](#php-json-http-client)

[![Build Status](https://camo.githubusercontent.com/e6268a4416657dac9a1af0acc81d6c5a3bf5385eb6da6d0c8bc07befbb8ad5f2/68747470733a2f2f7472617669732d63692e6f72672f6368726f6d612d782f7068702d6a736f6e2d687474702d636c69656e742e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/chroma-x/php-json-http-client)[![SensioLabs Insight](https://camo.githubusercontent.com/dee4b3f1be2f9155756e92e3faf9e01c7e866df3b5eb6114778d6b171da5caca/68747470733a2f2f696d672e736869656c64732e696f2f73656e73696f6c6162732f692f36623864623530362d313231612d343837352d386231642d3536306235303565303434342e737667)](https://insight.sensiolabs.com/projects/6b8db506-121a-4875-8b1d-560b505e0444)[![Code Climate](https://camo.githubusercontent.com/8dc0be27a40d5c9f1a2f66bfad31dcb2f4659287c8433c01bfd863656f039b40/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f6368726f6d612d782f7068702d6a736f6e2d687474702d636c69656e742f6261646765732f6770612e737667)](https://codeclimate.com/github/chroma-x/php-json-http-client)[![Latest Stable Version](https://camo.githubusercontent.com/652b7a0a3126a165544e78ddc66f48eeb05f06c95fc04515f3421fe36a92de77/68747470733a2f2f706f7365722e707567782e6f72672f6368726f6d612d782f6a736f6e2d687474702d636c69656e742f762f737461626c65)](https://packagist.org/packages/chroma-x/json-http-client)[![Total Downloads](https://camo.githubusercontent.com/242690b60c502a771d052669b9019a952d3873a7785e413e3ba7441c7dfcc2c8/68747470733a2f2f706f7365722e707567782e6f72672f6368726f6d612d782f6a736f6e2d687474702d636c69656e742f646f776e6c6f616473)](https://packagist.org/packages/chroma-x/json-http-client)[![License](https://camo.githubusercontent.com/4c97cb7551b282dc384c69cb12316454041e9851a8aea46fef21a5e992f6b240/68747470733a2f2f706f7365722e707567782e6f72672f6368726f6d612d782f6a736f6e2d687474702d636c69656e742f6c6963656e7365)](https://packagist.org/packages/chroma-x/json-http-client)

A JSON HTTP client library. This project also is the reference implementation for extending the [PHP Basic HTTP Client](https://github.com/chroma-x/php-basic-http-client).

Installation
------------

[](#installation)

```
{
   	"require": {
        "chroma-x/json-http-client": "~4.0"
    }
}

```

Usage
-----

[](#usage)

### Autoloading and namesapce

[](#autoloading-and-namesapce)

```
require_once('path/to/vendor/autoload.php');

```

### Simple usage

[](#simple-usage)

#### Preparing the HTTP client

[](#preparing-the-http-client)

```
use ChromaX\JsonHttpClient;
use ChromaX\BasicHttpClient\Request\Authentication;
use ChromaX\BasicHttpClient\Request\Message;

// Instantiating a basic HTTP client with the endpoints URL
// If the endpoint uses the `HTTPS` schema a `HttpsTransport` instance will be used automatically.
$client = new JsonHttpClient\JsonHttpClient('http://requestb.in/1aipzl31');

// Adding an authentication method
$client
	->getRequest()
	->addAuthentication(new Authentication\BasicAuthentication('username', 'password'));

```

#### Performing requests and read the response

[](#performing-requests-and-read-the-response)

##### Body-less requests (GET, HEAD and DELETE)

[](#body-less-requests-get-head-and-delete)

Perfoming the following `GET` request with additional query parameters

```
$response = $client->get(array(
	'paramName1' => 'paramValue1',
	'paramName2' => 'paramValue2'
));

```

will result in the following HTTP request.

```
GET /1aipzl31?paramName1=paramValue1&paramName2=paramValue2 HTTP/1.1
Host: requestb.in
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
User-Agent: PHP Basic HTTP Client 1.0
Accept: application/json
Content-Type: application/json

```

The same mechanic is offered to perform `HEAD` and `DELETE` requests wich all are body-less.

##### Body-full requests (POST, PUT, PATCH)

[](#body-full-requests-post-put-patch)

Perfoming the following `POST` request with body data

```
$response = $client->post(array(
	'paramName1' => 'paramValue1',
	'paramName2' => 'paramValue2',
	'paramName3' => array(
		'key1' => 'value1',
		'key2' => 'value2'
	)
));

```

will result in the following HTTP request.

```
POST /1aipzl31?paramName1=paramValue1&paramName2=paramValue2 HTTP/1.1
Host: requestb.in
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
User-Agent: PHP Basic HTTP Client 1.0
Accept: application/json
Content-Type: application/json
Content-Length: 102

{"paramName1":"paramValue1","paramName2":"paramValue2","paramName3":{"key1":"value1","key2":"value2"}}

```

The same mechanic is offered to perform `PUT` and `PATCH` requests wich all are body-full.

---

### Detailed usage

[](#detailed-usage)

The following example shows the usage with a more detailed configuration.

#### Configuring a HTTP Transport instance

[](#configuring-a-http-transport-instance)

```
use ChromaX\BasicHttpClient\Request\Transport\HttpTransport;

// Configuring a Transport instance
$transport = new HttpTransport();
$transport
	->setHttpVersion(HttpTransport::HTTP_VERSION_1_1)
	->setTimeout(5)
	->setReuseConnection(true)
	->setAllowCaching(true)
	->setFollowRedirects(true)
	->setMaxRedirects(10);

```

#### Configuring a HTTPS Transport instance

[](#configuring-a-https-transport-instance)

```
use ChromaX\BasicHttpClient\Request\Transport\HttpsTransport;

// Configuring a Transport instance
$transport = new HttpsTransport();
$transport
	->setHttpVersion(HttpsTransport::HTTP_VERSION_1_1)
	->setTimeout(5)
	->setReuseConnection(true)
	->setAllowCaching(true)
	->setFollowRedirects(true)
	->setMaxRedirects(10)
	->setVerifyPeer(true);

```

#### Configuring a Message instance with Body

[](#configuring-a-message-instance-with-body)

```
use ChromaX\BasicHttpClient\Request\Message\Cookie\Cookie;
use ChromaX\BasicHttpClient\Request\Message\Header\Header;
use ChromaX\BasicHttpClient\Request\Message\Message;
use ChromaX\JsonHttpClient\Request\Message\Body\JsonBody;

// Configuring a message Body instance
$messageBody = new JsonBody(array(
	'paramName1' => 'paramValue1',
	'paramName2' => 'paramValue2',
	'paramName3' => array(
		'key1' => 'value1',
		'key2' => 'value2'
	)
));

// Configuring a Message instance
$message = new Message();
$message
	->addHeader(new Header('Content-Type', array('application/json')))
	->addHeader(new Header('Accept', array('application/json')))
	->addHeader(new Header('Runscope-Bucket-Auth', array('7a64dde7-74d5-4eed-b170-a2ab406eff08')))
	->addCookie(new Cookie('PHPSESSID', ''))
	->setBody($messageBody);

```

##### Message and request Header instances

[](#message-and-request-header-instances)

**Please note, that headers have some unusual behaviours.** Header names have an uniform way of nomenclature so the following three getter calls would have the same result.

```
$header1 = $message->getHeaderByName('Content-Type');
$header2 = $message->getHeaderByName('content-type');
$header3 = $message->getHeaderByName('CONTENT-Type');

```

To allow multiple request headers using the same name, the method `addAdditionalHeader` provides such a logic.

```
// Add or replace a request header
$message->addHeader(new Header('Custom-Header', array('CustomHeaderValue')));
// Add a request header and keep the existing one untouched
$message->addAdditionalHeader(new Header('Custom-Header', array('AnotherCustomHeaderValue')));

```

#### Configuring an endpoints URL, build the Request instance and perform the HTTP request

[](#configuring-an-endpoints-url-build-the-request-instance-and-perform-the-http-request)

For more information about the usage of the URL object please take a look at the [PHP URL Util](https://github.com/chroma-x/php-url-util) project.

```
use ChromaX\BasicHttpClient\Request\Authentication\BasicAuthentication;
use ChromaX\JsonHttpClient\Request\JsonRequest;
use ChromaX\UrlUtil\Url;

// Setting up the endpoints URL
$url = new Url('https://john:secret@yourapihere-com-98yq3775xff0.runscope.net:443/path/to/resource?arg1=123#fragment');

// Configuring and performing a Request
$request = new JsonRequest();
$request
	->setUserAgent('PHP JSON HTTP Client Test 1.0')
	->setUrl($url)
	->addAuthentication(new BasicAuthentication('username', 'password'))
	->setMethod(JsonRequest::REQUEST_METHOD_POST)
	->setTransport($transport)
	->setMessage($message)
	->perform();

```

The resulting HTTP request would be the following.

```
POST /?paramName1=paramValue1&paramName2=paramValue2 HTTP/1.1
Host: yourapihere-com-98yq3775xff0.runscope.net
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
User-Agent: PHP JSON HTTP Client Test 1.0
Cookie: PHPSESSID=
Content-Type: application/json
Accept: application/json
Runscope-Bucket-Auth: 7a64dde7-74d5-4eed-b170-a2ab406eff08
Content-Length: 102

{"paramName1":"paramValue1","paramName2":"paramValue2","paramName3":{"key1":"value1","key2":"value2"}}

```

### Usage of authentication methods

[](#usage-of-authentication-methods)

You can add one or more Authentication instances to every Request instance. At the moment this project provides classes for [HTTP Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) and [SSL Client Certificate Authentication](https://en.wikipedia.org/wiki/Transport_Layer_Security#Client-authenticated_TLS_handshake).

#### HTTP Basic Authentication

[](#http-basic-authentication)

Required credentials are a *username* and a *password* that get provided to the class constructor as arguments.

```
use ChromaX\BasicHttpClient\Request\Authentication\BasicAuthentication;
use ChromaX\JsonHttpClient\Request\JsonRequest;

// Configuring the authentication
$basicAuthentication = new BasicAuthentication('username', 'password');

// Adding the authentication instance to the Request
$request = new JsonRequest();
$response = $request->addAuthentication($basicAuthentication);

```

#### SSL Client Certificate Authentication

[](#ssl-client-certificate-authentication)

Required credentials are a *Certificate Authority Certificate*, a *Client Certificate* and the password that is used to decrypt the Client Certificate that get provided to the class constructor as arguments.

```
use ChromaX\BasicHttpClient\Request\Authentication\ClientCertificateAuthentication;
use ChromaX\JsonHttpClient\Request\JsonRequest;

// Configuring the authentication
$clientCertificateAuthentication = new ClientCertificateAuthentication(
	'/var/www/project/clientCert/ca.crt',
	'/var/www/project/clientCert/client.crt',
	'clientCertPassword'
);

// Adding the authentication instance to the Request
$request = new JsonRequest();
$response = $request->addAuthentication($clientCertificateAuthentication);

```

---

Reading from the resulting Response object
------------------------------------------

[](#reading-from-the-resulting-response-object)

### Getting the response object

[](#getting-the-response-object)

If using the `JsonHttpClient` the response object is returned by the termination methods listed above. If directly using the JsonRequest instance, you can get the JsonResponse object via a getter.

```
// Getting the response ChromaX\BasicHttpClient\Response\JsonResponse object
$response = $request->getResponse();

// Reading the HTTP status code as integer; will return `200`
echo print_r($response->getStatusCode(), true) . PHP_EOL;

// Reading the HTTP status text as string; will return `HTTP/1.1 200 OK`
echo print_r($response->getStatusText(), true) . PHP_EOL;

// Reading the HTTP response headers as array of ChromaX\BasicHttpClient\Response\Header\Header objects
echo print_r($response->getHeaders(), true) . PHP_EOL;

// Reading the HTTP response body as associative array
echo print_r($response->getBody(), true) . PHP_EOL;

```

---

Getting effective Request information
-------------------------------------

[](#getting-effective-request-information)

After successful performing the request, the effective request information is tracked back to the JsonRequest object. They can get accessed as follows.

```
// Getting the effective endpoint URL including the query parameters
echo print_r($request->getEffectiveEndpoint(), true) . PHP_EOL;

// Getting the effective HTTP status, f.e. `POST /?paramName1=paramValue1&paramName2=paramValue2&paramName3=1&paramName4=42 HTTP/1.1`
echo print_r($request->getEffectiveStatus(), true) . PHP_EOL;

// Getting the effective raw request headers as string
echo print_r($request->getEffectiveRawHeader(), true) . PHP_EOL;

// Getting the effective request headers as array of `ChromaX\BasicHttpClient\Request\Message\Header\Header` objects
echo print_r($request->getEffectiveHeaders(), true) . PHP_EOL.PHP_EOL;

```

---

Getting some transactional statistics
-------------------------------------

[](#getting-some-transactional-statistics)

```
// Getting the statistics ChromaX\BasicHttpClient\Response\Statistics\Statistics object
$statistics = $request->getResponse()->getStatistics();

// Reading the redirection URL if the server responds with an redirect HTTP header and
// followRedirects is set to false
echo print_r($statistics->getRedirectEndpoint(), true).PHP_EOL;

// Reading the numbers of redirection as integer
echo print_r($statistics->getRedirectCount(), true).PHP_EOL;

// Getting the time in seconds the redirect utilized as float
echo print_r($statistics->getRedirectTime(), true).PHP_EOL;

// Getting the time in seconds that was utilized until the connection was established
echo print_r($statistics->getConnectionEstablishTime(), true).PHP_EOL;

// Getting the time in seconds that was utilized until the DNS hostname lookup was done
echo print_r($statistics->getHostLookupTime(), true).PHP_EOL;

// Getting the time in seconds that was utilized before the first data was sent
echo print_r($statistics->getPreTransferTime(), true).PHP_EOL;

// Getting the time in seconds that was utilized before the first data was received
echo print_r($statistics->getStartTransferTime(), true).PHP_EOL;

// Getting the time in seconds that was utilized to perfom the request an read the response
echo print_r($statistics->getTotalTime(), true).PHP_EOL;

```

---

Exception handling
------------------

[](#exception-handling)

PHP JSON HTTP Client provides different exceptions – also provided by the PHP Common Exceptions project – for proper handling.
You can find more information about [PHP Common Exceptions at Github](https://github.com/chroma-x/php-common-exceptions).

### Exceptions to be expected

[](#exceptions-to-be-expected)

In general you should expect that any setter method could thrown an `\InvalidArgumentException`. The following exceptions could get thrown while using PHP Basic HTTP Client.

- `ChromaX\CommonException\IoException\FileNotFoundException` on configuring a `ClientCertificateAuthentication`instance
- `ChromaX\CommonException\IoException\FileReadableException` on configuring a `ClientCertificateAuthentication`instance
- `ChromaX\BasicHttpClient\Exception\HttpRequestAuthenticationException` on performing a request
- `ChromaX\BasicHttpClient\Exception\HttpRequestException` on performing a request
- `ChromaX\CommonException\NetworkException\ConnectionTimeoutException` on performing a request
- `ChromaX\CommonException\NetworkException\CurlException` on performing a request
- `ChromaX\BasicHttpClient\Exception\HttpResponseException` if parsing the JSON response body fails

---

Contribution
------------

[](#contribution)

Contributing to our projects is always very appreciated.
**But: please follow the contribution guidelines written down in the [CONTRIBUTING.md](https://github.com/chroma-x/php-json-http-client/blob/master/CONTRIBUTING.md) document.**

License
-------

[](#license)

PHP JSON HTTP Client is under the MIT license.

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance34

Infrequent updates — may be unmaintained

Popularity18

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity87

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 55.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~188 days

Recently: every ~522 days

Total

17

Last Release

646d ago

Major Versions

0.2.0 → 1.0.02016-04-29

1.0.0 → 2.0.02016-05-02

2.0.0 → 3.0.02016-07-11

3.1.2 → 4.0.02024-08-02

PHP version history (4 changes)0.2.0PHP &gt;=5.3

3.1.0PHP ^7.1

3.1.2PHP ^7.1 || ^8.3

4.0.0PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/b7e993de6f3b4621aa41dc1e6907b57f8d478dd7e3cf23cdc0d7812cfe985647?d=identicon)[bonscho](/maintainers/bonscho)

---

Top Contributors

[![abmarkenwerk](https://avatars.githubusercontent.com/u/61745221?v=4)](https://github.com/abmarkenwerk "abmarkenwerk (5 commits)")[![Bonscho](https://avatars.githubusercontent.com/u/5921241?v=4)](https://github.com/Bonscho "Bonscho (3 commits)")[![andriusbaliutis](https://avatars.githubusercontent.com/u/77664629?v=4)](https://github.com/andriusbaliutis "andriusbaliutis (1 commits)")

---

Tags

basic-authenticationclient-certificatecomposer-packagehttp-clienthttps-clientjson-clientjson-requestphp-libraryrestful-clientssl-client-certificatejsonhttp clientsslrestfulbasic authClient Certificate Auth

### Embed Badge

![Health badge](/badges/markenwerk-json-http-client/health.svg)

```
[![Health](https://phpackages.com/badges/markenwerk-json-http-client/health.svg)](https://phpackages.com/packages/markenwerk-json-http-client)
```

###  Alternatives

[ismaeltoe/osms

PHP library wrapper of the Orange SMS API.

4540.0k](/packages/ismaeltoe-osms)[gte451f/phalcon-json-api-package

A set of tools designed for use in a Phalcon application to make a RESTish API

372.7k](/packages/gte451f-phalcon-json-api-package)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
