Documentation

Legacy mode

When creating an object for http-client, you can pass options as an array to the constructor (majority of options also already have setters):

OptionTypeDescription
redirect *boolEnable redirect (true true by default – redirect).
redirectMax *intMax. number of redirects (5 by default).
waitResponseboolStandby for response or disconnect immediately after query (true by default – wait for response).
socketTimeoutintConnection timeout in seconds (default value: 30).
streamTimeoutintStream timeout in seconds (default value: 60).
version *stringHTTP version (HttpClient::HTTP_1_0, HttpClient::HTTP_1_1) (default value: "1.0").
proxyHoststringProxy server Name\URL.
proxyPortintProxy server port.
proxyUserstringProxy server user name.
proxyPasswordstringProxy server password.
compressboolUse gzip compression (default value: false).
charsetstringEncoding for contents of POST and PUT queries.
disableSslVerificationboolIf true, no verification for SSL certificates is performed.
bodyLengthMaxintMaximum query length.
privateIpboolEnable queries to private IP-addresses (default value: true – enable).
debugLevelintDebugging level with constants HttpDebug::*.
cookies *arrayArray with cookie files for a HTTP query.
headers *arrayArray with titles for HTTP query.
useCurlboolEnable CURL library (default value: false).
curlLogFilestringFull path to file with CURL logs.

* – options, operating only in legacy mode.


Option values by default at a specific project can be defined in settings.php:

return [
	// ...
	"http_client_options" => [
		"value" => [
			"socketTimeout" => 20,
			"streamTimeout" => 20,
			"useCurl" => true,
		],
	]
	// ...
];

Main available methods:

Simple example:

use Bitrix\Main\Web\HttpClient;
	
$http = new HttpClient([
	'compress' => true,
	'headers' => [
		'User-Agent' => 'bitrix',
	],
]);
	
$result = $http->get('https://1c-bitrix.ru/');
	
if ($result !== false)
{
	var_dump($http->getStatus());
	var_dump($http->getHeaders());
}
else
{
	var_dump($http->getError());
}

Client will independently execute a redirect and will unpack a response.

The main 23.300.0 now has option to dynamically (contrary to the option waitResponse) define fetching for response body via callback function shouldFetchBody. Parameters for callback function receive response object with titles and a query object:

use Bitrix\Main\Web\HttpClient;
use Bitrix\Main\Web\Http\Response;
use Psr\Http\Message\RequestInterface; 
	
$http = new HttpClient();
	
$http->shouldFetchBody(function (Response $response, RequestInterface $request) {
	var_dump($request->getHeaders());
	return ($response->getHeadersCollection()->getContentType() === 'text/html');
});
	
$result = $http->get('https://www.bitrix24.com/');
var_dump($result);


© «Bitrix24», 2001-2024