Esempio n. 1
0
 public function testUploadArray()
 {
     $req = new HTTP_Request2(null, HTTP_Request2::METHOD_POST);
     $body = $req->addUpload('upload', array(array(dirname(dirname(__FILE__)) . '/_files/plaintext.txt', 'bio.txt', 'text/plain'), array(fopen(dirname(dirname(__FILE__)) . '/_files/empty.gif', 'rb'), 'photo.gif', 'image/gif')))->getBody();
     $asString = $body->__toString();
     $this->assertContains(file_get_contents(dirname(dirname(__FILE__)) . '/_files/empty.gif'), $asString);
     $this->assertContains('name="upload[0]"; filename="bio.txt"', $asString);
     $this->assertContains('name="upload[1]"; filename="photo.gif"', $asString);
     $body2 = $req->setConfig(array('use_brackets' => false))->getBody();
     $asString = $body2->__toString();
     $this->assertContains('name="upload"; filename="bio.txt"', $asString);
     $this->assertContains('name="upload"; filename="photo.gif"', $asString);
 }
Esempio n. 2
0
 public static function Post_Uri_Params($request_uri, $headers, $params, array $postFiles = null)
 {
     $request = new HTTP_Request2($request_uri, HTTP_Request2::METHOD_POST);
     $request->setHeader($headers)->addPostParameter($params);
     if (count($postFiles)) {
         foreach ($postFiles as $key => $value) {
             $request->addUpload($key, $value['tmp_name'], $value['name']);
         }
     }
     try {
         $response = $request->send();
         if (200 == $response->getStatus()) {
             return $response->getBody();
         } else {
             return false;
         }
     } catch (HTTP_Request2_Exception $e) {
         return false;
     }
 }
 public static function requestToPostMethod($argURL, $argParams = NULL, $argFiles = NULL, $argTimeOut = 60)
 {
     $HttpRequestObj = new HTTP_Request2();
     $urls = parse_url($argURL);
     if (isset($urls["user"]) && isset($urls["pass"])) {
         $HttpRequestObj->setAuth($urls["user"], $urls["pass"]);
     }
     if (isset($urls["port"])) {
         $url = $urls["scheme"] . '://' . $urls["host"] . ':' . $urls["port"];
     } else {
         $url = $urls["scheme"] . '://' . $urls["host"];
     }
     if (isset($urls["path"])) {
         $url .= $urls["path"];
     }
     $HttpRequestObj->setUrl($url);
     $HttpRequestObj->setMethod(HTTP_Request2::METHOD_POST);
     if ('https' === $urls["scheme"]) {
         $HttpRequestObj->setConfig(array('connect_timeout' => $argTimeOut, 'timeout' => $argTimeOut, 'adapter' => 'HTTP_Request2_Adapter_Curl', 'ssl_verify_peer' => FALSE, 'ssl_verify_host' => FALSE));
     } else {
         $HttpRequestObj->setConfig(array('connect_timeout' => $argTimeOut, 'timeout' => $argTimeOut));
     }
     if (is_array($argParams)) {
         foreach ($argParams as $key => $value) {
             $HttpRequestObj->addPostParameter($key, $value);
         }
     }
     // ファイルをアップロードする場合
     if (is_array($argFiles)) {
         foreach ($argFiles as $key => $value) {
             $HttpRequestObj->addUpload($key, $value);
         }
     }
     // リクエストを送信
     $response = $HttpRequestObj->send();
     // レスポンスのボディ部を表示
     return $response;
 }
Esempio n. 4
0
 public function testUpload()
 {
     $req = new HTTP_Request2(null, HTTP_Request2::METHOD_POST);
     $req->addUpload('upload', dirname(__FILE__) . '/_files/plaintext.txt');
     $headers = $req->getHeaders();
     $this->assertEquals('multipart/form-data', $headers['content-type']);
     try {
         $req->addUpload('upload_2', 'missing file');
     } catch (HTTP_Request2_Exception $e) {
         return;
     }
     $this->fail('Expected HTTP_Request2_Exception was not thrown');
 }
Esempio n. 5
0
 /**
  * Fetches a json response via HTTP request
  * @todo Support cookies (to allow login and similiar features)
  * @param string $url URL to get json from
  * @param array $data (optional) HTTP post data
  * @param boolean $secure (optional) Wheter to verify peer using SSL or not, default false
  * @param string $certificateFile (optional) Local certificate file for non public SSL certificates
  * @param array Set an optional HTTP Authentication method and supply its login credentials.
  *              The supplied array must comply with the following structure:
  * <pre class="brush: php">
  *              $httpAuth = array(
  *                  'httpAuthMethod'   => 'none|basic|disgest',
  *                  'httpAuthUsername' => '<username>',
  *                  'httpAuthPassword' => '<password>',
  *              );
  * </pre>
  * @return mixed Decoded JSON on success, false otherwise
  */
 public function getJson($url, $data = array(), $secure = false, $certificateFile = '', $httpAuth = array(), $files = array())
 {
     $request = new \HTTP_Request2($url, \HTTP_Request2::METHOD_POST);
     if (!empty($httpAuth)) {
         switch ($httpAuth['httpAuthMethod']) {
             case 'basic':
                 $request->setAuth($httpAuth['httpAuthUsername'], $httpAuth['httpAuthPassword'], \HTTP_Request2::AUTH_BASIC);
                 break;
             case 'disgest':
                 $request->setAuth($httpAuth['httpAuthUsername'], $httpAuth['httpAuthPassword'], \HTTP_Request2::AUTH_DIGEST);
                 break;
             case 'none':
             default:
                 break;
         }
     }
     foreach ($data as $name => $value) {
         $request->addPostParameter($name, $value);
     }
     if (!empty($files)) {
         foreach ($files as $fieldId => $file) {
             $request->addUpload($fieldId, $file);
         }
     }
     if ($this->sessionId !== null) {
         $request->addCookie(session_name(), $this->sessionId);
     }
     $request->setConfig(array('ssl_verify_host' => false, 'ssl_verify_peer' => false, 'follow_redirects' => true, 'strict_redirects' => true));
     $response = $request->send();
     //echo '<pre>';var_dump($response->getBody());echo '<br /><br />';
     $cookies = $response->getCookies();
     foreach ($cookies as &$cookie) {
         if ($cookie['name'] === session_name()) {
             $this->sessionId = $cookie['value'];
             break;
         }
     }
     if ($response->getStatus() != 200) {
         \DBG::msg(__METHOD__ . ' Request failed! Status: ' . $response->getStatus());
         \DBG::msg('URL: ' . $url);
         \DBG::dump($data);
         return false;
     }
     $body = json_decode($response->getBody());
     if ($body === NULL) {
         \DBG::msg(__METHOD__ . ' failed!');
         \DBG::dump($response->getBody());
     }
     return $body;
 }
Esempio n. 6
0
 function request($method, $url, $token, $params, $file)
 {
     $req = new HTTP_Request2($url);
     $req->setMethod($method == "get" ? 'GET' : 'POST');
     $req->setHeader("X-Gallery-Request-Method", $method);
     if ($token) {
         $req->setHeader("X-Gallery-Request-Key", $token);
     }
     foreach ($params as $key => $value) {
         $req->addPostParameter($key, is_string($value) ? $value : json_encode($value));
     }
     if ($file) {
         $req->addUpload("file", $file, basename($file), mime_content_type($file));
     }
     $response = $req->send();
     $status = $response->getStatus();
     switch ($status) {
         case 200:
         case 201:
             return json_decode($response->getBody());
         case 403:
             throw new Gallery3_Forbidden_Exception($response->getBody(), $status);
         default:
             throw new Gallery3_Exception($response->getBody(), $status);
     }
 }
$filename = '/etc/passwd';
try {
    // First step: get an available upload server
    $request = new HTTP_Request2('http://rapidshare.com/cgi-bin/rsapi.cgi?sub=nextuploadserver_v1');
    $server = $request->send()->getBody();
    if (!preg_match('/^(\\d+)$/', $server)) {
        throw new Exception("Invalid upload server: {$server}");
    }
    // Calculate file hash, we'll use it later to check upload
    if (false === ($hash = @md5_file($filename))) {
        throw new Exception("Cannot calculate MD5 hash of '{$filename}'");
    }
    // Second step: upload a file to the available server
    $uploader = new HTTP_Request2("http://rs{$server}l3.rapidshare.com/cgi-bin/upload.cgi", HTTP_Request2::METHOD_POST);
    // Adding the file
    $uploader->addUpload('filecontent', $filename);
    // This will tell server to return program-friendly output
    $uploader->addPostParameter('rsapi_v1', '1');
    $response = $uploader->send()->getBody();
    if (!preg_match_all('/^(File[^=]+)=(.+)$/m', $response, $m, PREG_SET_ORDER)) {
        throw new Exception("Invalid response: {$response}");
    }
    $rspAry = array();
    foreach ($m as $item) {
        $rspAry[$item[1]] = $item[2];
    }
    // Check that uploaded file has the same hash
    if (empty($rspAry['File1.4'])) {
        throw new Exception("MD5 hash data not found in response");
    } elseif ($hash != strtolower($rspAry['File1.4'])) {
        throw new Exception("Upload failed, local MD5 is {$hash}, uploaded MD5 is {$rspAry['File1.4']}");
Esempio n. 8
0
 /**
  * Sends the request to the Scribd API
  *
  * @param string $uri    The API URI to request
  * @param string $method The HTTP method to use
  *
  * @throws Services_Scribd_Exception
  * @return void
  */
 protected function sendRequest($uri, $method)
 {
     $config = array('timeout' => $this->timeout);
     $request = new HTTP_Request2($uri, $method, $config);
     $request->setHeader('User-Agent', '@package-name@-@package-version@');
     if ($this->requestAdapter !== null) {
         $request->setAdapter($this->requestAdapter);
     }
     if ($method === HTTP_Request2::METHOD_POST) {
         if (array_key_exists('file', $this->arguments)) {
             $request->addUpload('file', $this->arguments['file']);
             unset($this->arguments['file']);
         }
         $request = $request->addPostParameter($this->arguments);
     }
     try {
         $response = $request->send();
     } catch (HTTP_Request2_Exception $e) {
         throw new Services_Scribd_Exception($e->getMessage(), $e->getCode());
     }
     if ($response->getStatus() !== 200) {
         throw new Services_Scribd_Exception('Invalid response returned from server', $response->getStatus());
     }
     return $response->getBody();
 }
require_once 'HTTP/OAuth.php';
require_once 'HTTP/OAuth/Consumer/Request.php';
require_once 'HTTP/Request2.php';

// Set up HTTP request
$httpRequest = new HTTP_Request2;
$httpRequest->setHeader('Accept-Encoding', '.*');

// Handle file uploads
if (isset($params['file'])) {
   // Content of multipart forms isn't signed according to the OAuth specs.
   // We handle this case by manually building the content of the multipart request
   // and then sending no params to the OAuth lib for signing.
   foreach ($params as $key => $val) {
     if ($key=='file') {
        $httpRequest->addUpload($key, $val);
     } else {
        $httpRequest->addPostParameter($key, $val);
     }
   }
   $params = array();
}

// Set up OAuth consumer
$request = new HTTP_OAuth_Consumer_Request;
$request->accept($httpRequest);
$consumer = new HTTP_OAuth_Consumer($visualplatform_config['key'], $visualplatform_config['secret'], $visualplatform_config['token'], $visualplatform_config['token_secret']);
$consumer->accept($request);

// Make request
$response = $consumer->sendRequest("http://" . $visualplatform_config['domain'] . $endpoint, $params, "POST");
Esempio n. 10
0
 // 65秒待つ
 $HttpRequest->setConfig(array('timeout' => 65, 'adapter' => 'HTTP_Request2_Adapter_Curl', 'ssl_verify_peer' => FALSE, 'ssl_verify_host' => FALSE));
 eval('$HttpRequest->setMethod(HTTP_Request2::METHOD_' . $method . ');');
 if (count($posts) > 0) {
     foreach ($posts as $keysKey => $keysVal) {
         $HttpRequest->addPostParameter($keysKey, $keysVal);
     }
 }
 if (count($cookies) > 0) {
     foreach ($cookies as $keysKey => $keysVal) {
         $HttpRequest->addCookie($keysKey, $keysVal);
     }
 }
 if (count($uploads) > 0) {
     for ($uploadCnt = 0; count($uploads) > $uploadCnt; $uploadCnt++) {
         $HttpRequest->addUpload($uploads[$uploadCnt]['formname'], $uploads[$uploadCnt]['filepath'], $uploads[$uploadCnt]['filename']);
     }
 }
 echo PHP_EOL;
 echo '【Response】' . PHP_EOL;
 $Response = $HttpRequest->send();
 //print_r($HttpRequest);
 $statusCode = $Response->getStatus();
 if (200 == $statusCode) {
     echo 'status code: ' . $Response->getStatus() . PHP_EOL;
     foreach ($Response->getHeader() as $key => $value) {
         echo $key . ': ' . $value . PHP_EOL;
     }
 } else {
     echo 'Unexpected HTTP status: ' . $statusCode . ' ' . $Response->getReasonPhrase();
 }
 /**
  *
  * @expectedException HTTP_Request2_LogicException
  * @expectedExceptionMessage missing file
  */
 public function testUpload()
 {
     $req = new HTTP_Request2(null, HTTP_Request2::METHOD_POST);
     $req->addUpload('upload', dirname(__FILE__) . '/_files/plaintext.txt');
     $headers = $req->getHeaders();
     $this->assertEquals('multipart/form-data', $headers['content-type']);
     $req->addUpload('upload_2', 'missing file');
 }
Esempio n. 12
0
 /**
  * Call a method on the Eventful API.
  *
  * @access  public
  * @param   string      arguments
  */
 function call($method, $args = array(), $type = 'json')
 {
     /* Methods may or may not have a leading slash.  */
     $method = trim($method, '/ ');
     /* Construct the URL that corresponds to the method.  */
     $url = $this->api_root . '/' . $type . '/' . $method;
     $this->_request_uri = $url;
     // Handle the OAuth request.
     if ($this->using_oauth) {
         //create a new Oauth request.  By default this uses the HTTP AUTHORIZATION headers and HMACSHA1 signature
         if ($this->debug) {
             echo "Checking on this consumer key/secret {$this->conskey} / {$this->conssec} <br>\n";
             echo "Checking on this token key/secret {$this->oauth_token} / {$this->oauth_token_secret} <br>\n";
             echo "Using the app_key {$this->app_key} <br>\n";
         }
         $config = array('consumer_key' => $this->conskey, 'consumer_secret' => $this->conssec, 'token' => $this->oauth_token, 'secret' => $this->oauth_token_secret, 'method' => 'POST', 'use_ssl' => false, 'user_agent' => 'Eventful_PHP_API');
         $tmhOAuth = new tmhOauth($config);
         $multipart = false;
         $app_key_name = 'app_key';
         foreach ($args as $key => $value) {
             if (preg_match('/_file$/', $key)) {
                 // Check for file_upload
                 $multipart = true;
                 $app_key_name = 'oauth_app_key';
                 // Have to store the app_key in oauth_app_key so it gets sent over in the Authorization header
             }
         }
         $code = $tmhOAuth->user_request(array('method' => 'POST', 'url' => $tmhOAuth->url($url, ''), 'params' => array_merge(array($app_key_name => $this->{app_key}), $args), 'multipart' => $multipart));
         if ($code == 200) {
             $resp = $tmhOAuth->response['response'];
             $this->_response_data = $resp;
             if ($type == "json") {
                 $data = json_decode($resp, true);
                 if ($data[error] > 0) {
                     return PEAR::raiseError('Invalid status : ' . $data[status] . ' (' . $data[description] . ')', $data);
                 }
             } else {
                 $data = new SimpleXMLElement($resp);
                 if ($data->getName() === 'error') {
                     $error = $data['string'] . ": " . $data->description;
                     $code = $data['string'];
                     return PEAR::raiseError($error, $code);
                 }
             }
             return $data;
         } else {
             // Non 200 response code.
             return PEAR::raiseError('Invalid Response Code: ' . $code, $tmhOAuth->response['error']);
         }
     }
     // No OAuth just do a simple request
     $req = new HTTP_Request2($url);
     /* $req = new HTTP_Request2('http://api.eventful.com/rest/events/get'); */
     $req->setMethod(HTTP_Request2::METHOD_POST);
     /* Add each argument to the POST body.  */
     $req->addPostParameter('app_key', $this->app_key);
     foreach ($args as $key => $value) {
         if (preg_match('/_file$/', $key)) {
             // Treat file parameters differently.
             $req->addUpload($key, $value);
         } elseif (is_array($value)) {
             foreach ($value as $instance) {
                 $req->addPostParameter($key, $instance);
             }
         } else {
             $req->addPostParameter($key, $value);
         }
     }
     /* Send the request and handle basic HTTP errors.  */
     $response = $req->send();
     //echo " we got this status => " .  $response->getReasonPhrase() . $response->getStatus() ."\n";
     if ($response->getStatus() !== 200) {
         return PEAR::raiseError('Invalid Response Code: ' . $response->getReasonPhrase(), $response->getStatus());
     }
     if ($type == 'rest') {
         /* Process the response XML through SimpleXML */
         $resp_data = $response->getBody();
         $this->_response_data = $resp_data;
         $data = new SimpleXMLElement($resp_data);
         /* Check for call-specific error messages */
         if ($data->getName() === 'error') {
             $error = $data['string'] . ": " . $data->description;
             $code = $data['string'];
             return PEAR::raiseError($error, $code);
         }
         return $data;
     }
     $resp_data = $response->getBody();
     $this->_response_data = $resp_data;
     $data = json_decode($resp_data, true);
     //$data = json_encode($response->getBody());
     return $data;
 }