Skip to content

Instantly share code, notes, and snippets.

@gboddin
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gboddin/a9499385e388f48378f9 to your computer and use it in GitHub Desktop.
Save gboddin/a9499385e388f48378f9 to your computer and use it in GitHub Desktop.
Http JSON client class for REST API (like elasticsearch)
<?php
class HttpJsonClient {
static function GET($url,$body=null) {
return self::request('GET',$url,$body);
}
static function PUT($url,$body=null) {
return self::request('PUT',$url,$body);
}
static function DELETE($url,$body=null) {
return self::request('DELETE',$url,$body);
}
static function POST($url,$body=null) {
return self::request('POST',$url,$body);
}
static function setProxy($proxy) {
putenv('http_proxy='.$proxy);
}
static function disableProxy() {
putenv('http_proxy');
}
static private function request($method,$url,$body) {
if(is_array($body))
$body = json_encode($body);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
if(!is_null($body)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($body))
);
}
$data = trim(curl_exec($ch));
return json_decode($data,true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment