Last active
August 29, 2015 14:08
-
-
Save gboddin/a9499385e388f48378f9 to your computer and use it in GitHub Desktop.
Http JSON client class for REST API (like elasticsearch)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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