forked from williamswebworks/php-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RESTClient.php
84 lines (73 loc) · 2.43 KB
/
RESTClient.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
/*
Thanks George A. Papayiannis, most codes of this file are from
http://www.sematopia.com/2006/10/how-to-making-a-php-rest-client-to-call-rest-resources/
*/
require_once "HTTP/Request.php";
class RESTClient {
private $curr_url = "";
private $user_name = "";
private $password = "";
private $content_type = "";
private $response = "";
private $responseBody = "";
private $responseCode = "";
private $req = null;
public function __construct($user_name="", $password="", $content_type="") {
$this->user_name = $user_name;
$this->password = $password;
$this->content_type = $content_type;
return true;
}
public function createRequest($url, $method, $arr = null) {
$this->curr_url = $url;
$this->req = new HTTP_Request($url);
if ($this->user_name != "" && $this->password != "") {
$this->req->setBasicAuth($this->user_name, $this->password);
}
if ($this->content_type != "") {
$this->req->addHeader("Content-Type", $this->content_type);
}
switch($method) {
case "GET":
$this->req->setMethod(HTTP_REQUEST_METHOD_GET);
break;
case "POST":
$this->req->setMethod(HTTP_REQUEST_METHOD_POST);
$this->addPostData($arr);
break;
case "PUT":
$this->req->setMethod(HTTP_REQUEST_METHOD_PUT);
$this->addPostData($arr);
break;
case "DELETE":
$this->req->setMethod(HTTP_REQUEST_METHOD_DELETE);
break;
}
}
private function addPostData($arr) {
if ($arr != null) {
if (gettype($arr) == 'string') {
$this->req->setBody($arr);
} else {
foreach ($arr as $key => $value) {
$this->req->addPostData($key, $value);
}
}
}
}
public function sendRequest() {
$this->response = $this->req->sendRequest();
if (PEAR::isError($this->response)) {
echo $this->response->getMessage();
die();
} else {
$this->responseCode = $this->req->getResponseCode();
$this->responseBody = $this->req->getResponseBody();
}
}
public function getResponse() {
return array($this->responseCode, $this->responseBody);
}
}
?>