public function retrieve_user_details() { // Get the stream to the user page via the Snipt API $request = new HTTPRequest(SNIPT_API . SNIPT_USER . SNIPT_FORMAT, HTTP_METH_GET); echo "Connecting to Snipt API....\n"; $request->send(); if ($request->getResponseCode() == 200) { $this->user_details = json_decode($request->getResponseBody()); echo "Snipt entries to retrieve : {$this->user_details->count}\n"; foreach ($this->user_details->snipts as $snipt) { // Retrieve the snipt entry $request = new HTTPRequest(SNIPT_API . SNIPT_SNIPT . $snipt . "." . SNIPT_FORMAT . SNIPT_STYLE); $request->send(); if ($request->getResponseCode() == 200) { $this->snipts[$snipt] = json_decode($request->getResponseBody()); } else { echo "[ERROR] Could not retrieve the data for snipt entry {$snipt}\n"; } } return true; } else { echo "Invalid data received, exiting....\n"; return false; } }
/** * Sends the HTTP message [Request] to a remote server and processes * the response. * * @param Request $request request to send * @param Response $request response to send * @return Response */ public function _send_message(Request $request, Response $response) { $http_method_mapping = array(HTTP_Request::GET => HTTPRequest::METH_GET, HTTP_Request::HEAD => HTTPRequest::METH_HEAD, HTTP_Request::POST => HTTPRequest::METH_POST, HTTP_Request::PUT => HTTPRequest::METH_PUT, HTTP_Request::DELETE => HTTPRequest::METH_DELETE, HTTP_Request::OPTIONS => HTTPRequest::METH_OPTIONS, HTTP_Request::TRACE => HTTPRequest::METH_TRACE, HTTP_Request::CONNECT => HTTPRequest::METH_CONNECT); // Create an http request object $http_request = new HTTPRequest($request->uri(), $http_method_mapping[$request->method()]); if ($this->_options) { // Set custom options $http_request->setOptions($this->_options); } // Set headers $http_request->setHeaders($request->headers()->getArrayCopy()); // Set cookies $http_request->setCookies($request->cookie()); // Set query data (?foo=bar&bar=foo) $http_request->setQueryData($request->query()); // Set the body if ($request->method() == HTTP_Request::PUT) { $http_request->addPutData($request->body()); } else { $http_request->setBody($request->body()); } try { $http_request->send(); } catch (HTTPRequestException $e) { throw new Request_Exception($e->getMessage()); } catch (HTTPMalformedHeaderException $e) { throw new Request_Exception($e->getMessage()); } catch (HTTPEncodingException $e) { throw new Request_Exception($e->getMessage()); } // Build the response $response->status($http_request->getResponseCode())->headers($http_request->getResponseHeader())->cookie($http_request->getResponseCookies())->body($http_request->getResponseBody()); return $response; }
public function decode($point = array('lat' => null, 'lng' => null)) { $uri = 'http://apis.map.qq.com/ws/geocoder/v1?location=' . $point['lat'] . ',' . $point['lng'] . '&output=json&key=' . $this->conf['key']; $http = new \HTTPRequest($uri, HTTP_METH_GET); $http->send(); $code = $http->getResponseCode(); if ($code != 200) { throw new Exception('http error', $code); } $r = json_decode($http->getResponseBody(), true); if (!isset($r['result']['address'])) { throw new Exception($r['message'], $r['status']); } return array('address' => $r['result']['address']); }
public function decode($point = array('lat' => null, 'lng' => null)) { $uri = 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&latlng=' . $point['lat'] . ',' . $point['lng']; $http = new \HTTPRequest($uri, HTTP_METH_GET); if (isset($this->conf['lang'])) { $http->addHeaders(array('Accept-Language' => $this->conf['lang'])); } $http->send(); $code = $http->getResponseCode(); if ($code != 200) { throw new Exception('http error', $code); } $r = json_decode($http->getResponseBody(), true); if (!isset($r['results'][0]['formatted_address'])) { throw new Exception($r['status'], -1); } return array('address' => $r['results'][0]['formatted_address']); }
/** * 上传文件,要token认证 * @example shell curl -i -F 'file=@2.jpg' -F 'token=asdf' -F 'key=2.jpg' 'http://up.qiniu.com/' * @example shell ./qrsync ./conf.json * @return array array( "httpUri" => "http://com-163-sinkcup-test.qiniudn.com/1.jpg", "httpsUri" => "https://dn-com-163-sinkcup-test.qbox.me/1.jpg", } */ public function uploadFile($localPath, $remoteFileName, $headers = array()) { $remoteFileName = str_replace('/', '', $remoteFileName); $uri = 'http://' . str_replace('//', '/', $this->conf['host']['up'] . '/'); //scope中指定文件,就可以覆盖。如果只写bucket,则重复上传会出现错误:614 文件已存在。 $policy = array('scope' => $this->bucket . ':' . $remoteFileName, 'deadline' => time() + 3600); $pics = array('image/jpeg', 'image/webp', 'image/png'); //如果是图片,则需要返回分辨率 if (isset($headers['Content-Type']) && in_array($headers['Content-Type'], $pics)) { $policy['returnBody'] = json_encode(array('width' => '$(imageInfo.width)', 'height' => '$(imageInfo.height)')); } $data = $this->encode(json_encode($policy)); $token = $this->sign($data) . ':' . $data; //$hash = hash_file('crc32b', $localPath); //$tmp = unpack('N', pack('H*', $hash)); $fields = array('token' => $token, 'key' => $remoteFileName); $http = new \HTTPRequest($uri, HTTP_METH_POST); $contentType = isset($headers['Content-Type']) ? $headers['Content-Type'] : 'multipart/form-data'; $http->addPostFile('file', $localPath, $contentType); $http->addPostFields($fields); //$http->setHeader($headers); $http->send(); $body = json_decode($http->getResponseBody(), true); $code = $http->getResponseCode(); if ($code == 200) { //自定义域名一定是http,因为证书不能跨域名 if (!isset($this->conf['customDomain']) || empty($this->conf['customDomain'])) { $httpUri = 'http://' . str_replace('//', '/', $this->bucket . $this->conf['httpUriSuffix'] . '/' . $remoteFileName); } else { $httpUri = 'http://' . $this->conf['customDomain'] . '/' . $remoteFileName; } $r = array('httpUri' => $httpUri, 'httpsUri' => 'https://' . str_replace('//', '/', $this->conf['httpsUriPrefix'] . $this->bucket . $this->conf['httpsUriSuffix'] . '/' . $remoteFileName)); if (isset($body['width'])) { $r['width'] = $body['width']; } if (isset($body['height'])) { $r['height'] = $body['height']; } return $r; } throw new Exception($body['error'], $code); }
/** * Execute the request using the PECL HTTP extension. (recommended) * * @param Request $request Request to execute * @return Response */ protected function _http_execute(Request $request) { $http_method_mapping = array(HTTP_Request::GET => HTTPRequest::METH_GET, HTTP_Request::HEAD => HTTPRequest::METH_HEAD, HTTP_Request::POST => HTTPRequest::METH_POST, HTTP_Request::PUT => HTTPRequest::METH_PUT, HTTP_Request::DELETE => HTTPRequest::METH_DELETE, HTTP_Request::OPTIONS => HTTPRequest::METH_OPTIONS, HTTP_Request::TRACE => HTTPRequest::METH_TRACE, HTTP_Request::CONNECT => HTTPRequest::METH_CONNECT); // Create an http request object $http_request = new HTTPRequest($request->uri(), $http_method_mapping[$request->method()]); // Set custom options $http_request->setOptions($this->_options); // Set headers $http_request->setHeaders($request->headers()->getArrayCopy()); // Set cookies $http_request->setCookies($request->cookie()); // Set body $http_request->setBody($request->body()); try { $http_request->send(); } catch (HTTPRequestException $e) { throw new Kohana_Request_Exception($e->getMessage()); } catch (HTTPMalformedHeaderException $e) { throw new Kohana_Request_Exception($e->getMessage()); } catch (HTTPEncodingException $e) { throw new Kohana_Request_Exception($e->getMessage()); } // Create the response $response = $request->create_response(); // Build the response $response->status($http_request->getResponseCode())->headers($http_request->getResponseHeader())->cookie($http_request->getResponseCookies())->body($http_request->getResponseBody()); return $response; }
<?php $url = "http://requestb.in/example"; $data = array("name" => "Lorna", "email" => "*****@*****.**"); $request = new HTTPRequest($url, HTTP_METH_POST); $request->setPostFields($data); $request->setHeaders(array("Content-Type" => "application/javascript")); $request->send(); $result = $request->getResponseBody(); var_dump($result);
function replace($photo, $photo_id, $async = null) { $upload_req = new HTTPRequest(); $upload_req->setMethod("POST"); $upload_req->setURL($this->Replace); //$upload_req->clearPostData(); //Process arguments, including method and login data. $args = array("api_key" => $this->api_key, "photo_id" => $photo_id, "async" => $async); if (!empty($this->email)) { $args = array_merge($args, array("email" => $this->email)); } if (!empty($this->password)) { $args = array_merge($args, array("password" => $this->password)); } if (!empty($this->token)) { $args = array_merge($args, array("auth_token" => $this->token)); } elseif (!empty($_SESSION['phpFlickr_auth_token'])) { $args = array_merge($args, array("auth_token" => $_SESSION['phpFlickr_auth_token'])); } ksort($args); $auth_sig = ""; foreach ($args as $key => $data) { if ($data !== null) { $auth_sig .= $key . $data; $upload_req->addPostData($key, $data); } } if (!empty($this->secret)) { $api_sig = md5($this->secret . $auth_sig); $upload_req->addPostData("api_sig", $api_sig); } $photo = realpath($photo); $result = $upload_req->addFile("photo", $photo); //Send Requests if ($upload_req->sendRequest()) { $this->response = $upload_req->getResponseBody(); } else { die("There has been a problem sending your command to the server."); } if ($async == 1) { $find = 'ticketid'; } else { $find = 'photoid'; } $rsp = explode("\n", $this->response); foreach ($rsp as $line) { if (ereg('<err code="([0-9]+)" msg="(.*)"', $line, $match)) { if ($this->die_on_error) { die("The Flickr API returned the following error: #{$match[1]} - {$match[2]}"); } else { $this->error_code = $match[1]; $this->error_msg = $match[2]; $this->parsed_response = false; return false; } } elseif (ereg("<" . $find . ">(.*)</", $line, $match)) { $this->error_code = false; $this->error_msg = false; return $match[1]; } } }
/** * 发送notification或message。请阅读友盟文档。 */ public function send($data) { $token = $this->grantToken(); $newData = $data; foreach ($token as $k => $v) { $newData[$k] = $v; } //必填 消息发送类型,其值为unicast,listcast,broadcast,groupcast或customizedcast if (!isset($data['type'])) { throw new Exception('need param: type'); } // 可选 当type=customizedcast时,开发者填写自己的alias,友盟根据alias进行反查找,得到对应的device_token。多个alias时用英文逗号分,不能超过50个。 if (isset($data['alias']) && !empty($data['alias'])) { if (is_array($data['alias'])) { $newData['alias'] = implode(',', $data['alias']); } else { $newData['alias'] = $data['alias']; } } // 必填 消息类型,值为notification或者message if (!isset($data['payload']['display_type'])) { $newData['payload']['display_type'] = 'notification'; } // 必填 通知栏提示文字。但实际没有用,todo确认 if (!isset($data['payload']['body']['ticker'])) { $newData['payload']['body']['ticker'] = $data['payload']['body']['title']; } //可选 消息描述。用于友盟推送web管理后台,便于查看。 if (!isset($data['description'])) { $newData['description'] = $data['payload']['body']['title']; } $defaultTrueParams = array('play_vibrate', 'play_lights', 'play_sound'); foreach ($defaultTrueParams as $one) { if (isset($data['payload']['body'][$one]) && ($data['payload']['body'][$one] == false || $data['payload']['body'][$one] == 'false')) { $newData['payload']['body'][$one] = 'false'; } } $http = new \HTTPRequest($this->conf['api_uri_prefix'] . 'api/send', HTTP_METH_POST); $http->setBody(json_encode($newData)); $http->send(); $body = $http->getResponseBody(); if ($http->getResponseCode() != 200) { throw new Exception($body); } $tmp = json_decode($body, true); if (!isset($tmp['ret']) || $tmp['ret'] != 'SUCCESS') { throw new Exception($body); } return true; }
/* * Doc Raptor simple PHP example * requires pecl_http extension * * This is a simple example of creating an excel file and saving it * using Doc Raptor * * For other usage and examples, visit: * http://docraptor.com/examples * * Doc Raptor http://docraptor.com * Expected Behavior http://www.expectedbehavior.com */ <?php $api_key = "YOUR_API_KEY_HERE"; $url = "https://docraptor.com/docs?user_credentials={$api_key}"; $document_content = "<table><tr><td>Cell</td></tr></table>"; $request = new HTTPRequest($url, HTTP_METH_POST); $request->setPostFields(array('doc[document_content]' => $document_content, 'doc[document_type]' => 'xls', 'doc[name]' => 'my_doc.xls', 'doc[test]' => 'true')); $request->send(); $file = fopen("my_excel_doc.xls", "w"); fwrite($file, $request->getResponseBody()); fclose($file); ?>
$LineLength = 40; $ReturnData = new stdClass(); $QuotesData = ""; // choose a RSS host $Site = $RSS[rand(0, count($RSS) - 1)]; // load news file if older than 15 minutes $time = file_exists($CacheDir . $Site["cache"]) ? filemtime($CacheDir . $Site["cache"]) : 0; if ($time < time() - 15 * 60 || true) { $fp = fopen($CacheDir . $Site["cache"], "w"); try { $hrp = new HTTPRequest($Site["url"]); $hrp->send(); } catch (HttpException $x) { echo $x; } $newsRSS = $hrp->getResponseBody(); fwrite($fp, $newsRSS); fclose($fp); } else { $newsRSS = file_get_contents($CacheDir . $Site["cache"]); } $news = simplexml_load_string(trim($newsRSS)); $QuotesData .= "<img src=\"" . $Site["logo"] . "\" id='content-logo'/>"; $QuotesData .= "<ul>"; $i = 1; foreach ($news->channel->item as $k => $it) { if ($i > 4) { break; } $desc = ""; $it->description = preg_replace("/\\<([^\\<\\>]+)\\>/ui", "", $it->description);