API Sample Scripts 1.1/ru
From Aviberry API
К содержанию
Возникли вопросы?
Здесь Вы найдете примеры использования API на популярных языках для интеграции сервиса Aviberry с Вашим сайтом.
Contents |
Пример для PHP
Для проверки работы скрипта загрузите файл example.html и скрипт обработки action.php на Ваш сервер, измените значения YOUR API KEY и YOUR API PASS на Ваши данные и откройте в браузере страницу example.html.
example.html file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Aviberry Demo Script</title> <style type="text/css"> form table { width: 100%; } .col1 { width: 20%; } .col2 { width: 80%; } .text { width: 70%; } option { padding-left: 20px; } .submit { margin-top: 10px; padding: 0 5px 0 5px; } </style> </head> <body> <h1>Aviberry Demo Script</h1> <form action="action.php" method="post"> <table> <tr> <td class="col1">URL-aдрес исходного файла [HTTP/FTP/S3]</td> <td class="col2"> <input type="text" class="text" name="source_url" /> </td> </tr> <tr> <td>URL-aдрес целевого файла [FTP/S3/mailto]</td> <td> <input type="text" class="text" name="target_url" /> </td> </tr> <tr> <td>Формат</td> <td> <select name="format_id"> <option value="">Выберите...</option> <optgroup label="Video:"> <option value="16500">AVI video, Xvid (.avi)</option> <option value="16505">MPEG-4 video (.mp4)</option> <option value="16501">MPEG-2 video (.mpeg)</option> <option value="16503">WMV (.wmv)</option> <option value="16508">QuickTime (mov)</option> <option value="16523">3GPP for cellphone (.3gp)</option> <option value="16506">3GPP2 for cellphone (.3gp2)</option> <option value="16509">Flash video (.flv)</option> <option value="16520">WebM (.webm)</option> </optgroup> <optgroup label="Audio:"> <option value="16511">MP3 audio (.mp3)</option> </optgroup> </select> </td> </tr> <tr> <td> </td> <td> </td> </tr> <tr> <td></td> <td> <input type="submit" class="submit" value="Convert!" /> </td> </tr> </table> </form> </body> </html>
action.php file
<?php // // Main. // set_exception_handler('handleException'); // // Validate the request. // if ( (!isset($_POST['source_url']) || empty($_POST['source_url'])) || (!isset($_POST['target_url']) || empty($_POST['target_url'])) || (!isset($_POST['format_id']) || empty($_POST['format_id'])) ) { die('Bad request.'); } // // Build URL to access API. // define('AVIBERRY_API_HOST', 'www.aviberry.com'); define('AVIBERRY_API_KEY', ''); // Specify yours. define('AVIBERRY_API_PASS', ''); // Specify yours. define('AVIBERRY_API_VERSION', 'v1.1'); define('AVIBERRY_API_PROTOCOL', 'json'); define('AVIBERRY_API_URL_AUTHORIZED', 'http://' . AVIBERRY_API_KEY . ':' . AVIBERRY_API_PASS . '@' . AVIBERRY_API_HOST . '/api/' . AVIBERRY_API_VERSION . '/' . AVIBERRY_API_PROTOCOL . '/'); // // Prepare the request. // $methodName = 'startConversion'; $methodParams = array(); $methodParams['source_url'] = $_POST['source_url']; $methodParams['target_url'] = $_POST['target_url']; $methodParams['preset']['format_id'] = $_POST['format_id']; $request = array(); $request['version'] = '1.1'; $request['method'] = $methodName; $request['params'] = $methodParams; $request = json_encode($request); // // Send request. // try { $response = sendRequest(AVIBERRY_API_URL_AUTHORIZED, $request); } catch(Exception $e) { throw new Exception('Unable to start conversion: ' . $e->getMessage()); } // // Process response. // $response = json_decode($response, true); if (isset($response['error'])) throw new Exception('Unable to start conversion: ' . $response['error']['message'], $response['error']['code']); // // Print result. // die('<div class="message">' . htmlspecialchars(sprintf('Conversion scheduled. ID: "%s".', $response['result'])) . '</div>' ); // // Functions. // /** * Performs HTTP POST. */ function sendRequest($url, $request) { $response = ''; $opts = array ( 'http' => array ( 'method' => 'POST', 'header' => 'Content-type: application/json', 'content' => $request ) ); $context = stream_context_create($opts); $fp = @fopen($url, 'r', false, $context); if (!is_resource($fp)) throw new Exception('Can\'t access API.'); while (!feof($fp)) $response .= fread($fp, 8192); return $response; } /** * Displays error. */ function handleException($e) { die('<div class="error">' . htmlspecialchars($e->getMessage()) . '</div>'); } ?>
Пример для C#
Для использования примера необходимо подставить свои значения вместо YOUR API KEY и YOUR API PASS.
using System.Collections.Generic; using System.IO; using System.Net; using System.Text; namespace Test { class Program { // Метод запрашивает API Aviberry. Параметры: // username - имя пользователя // password - пароль // protocol - протокол, для работы по XML RPC должно быть "xml" // method - название вызываемого метода // parameters - параметры static string RequestAviberryAPI(string username, string password, string protocol, string method, Dictionary parameters) { // Составляем строку запроса GET string parameterString = ""; Dictionary.Enumerator enumerator = parameters.GetEnumerator(); while (enumerator.MoveNext()) { if (parameterString.Length > 0) parameterString += "&"; parameterString += enumerator.Current.Key + "=" + enumerator.Current.Value; } string url = @"http://" + username + ":" + password + "@aviberry.com/api/v1.1/" + protocol + "/" + method + "?" + parameterString; NetworkCredential credentials = new NetworkCredential(username, password); // Строим HTTP-запрос HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Credentials = credentials; request.Method = "GET"; try { // Отправляем запрос на сервер HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string result = reader.ReadToEnd(); reader.Close(); // Возвращаем ответ сервера return result; } catch (WebException ex) { // Сюда мы попадём, если что-то пошло не так, и вернём текст с описанием ошибки return ex.Message; } } // Главный метод, здесь пример начинает работу static void Main(string[] args) { // Подготавливаем параметры Dictionary parameters = new Dictionary(); // Так можно добавлять параметры: parameters[имя параметра] = "значение параметра"; //parameters["param1"] = "value1"; //parameters["param2"] = "value2"; // Вызываем метод getTraffic от имени пользователя string response = RequestAviberryAPI("YOUR API KEY", "YOUR API PASS", "xml", "getTraffic", parameters); } } }
Пример JSON-RPC сервера с Callback
Пример JSON-RPC сервера можно скачать по ссылке aviberry.com_rpc_server_example.zip.
json_rpc_server_example.php file
<?php /** * Aviberry JSON-RPC server example. * * @link http://www.aviberry.com */ set_time_limit(60 * 60); if(!class_exists('DateTime')) require_once('DateTime.class.php'); //get it at http://code.google.com/p/json-xml-rpc/ require_once 'RPCServer.class.php'; //get it at http://code.google.com/p/json-xml-rpc/ header('Cache-Control: no-cache'); header('Pragma: no-cache'); $server = RPCServer::getInstance(); //note that the RPCServer class is a singleton /** * Callback method example * * @param array $conversion see http://api.aviberry.com/Methods_1.1#getConversion for details * * @return boolean success * * @link http://api.aviberry.com/Methods_1.1#startConversion * @link http://api.aviberry.com/Methods_1.1#getConversion */ function conversionEndCallback($conversion) { //converted successfully if(!$conversion['error_code']){ //your code here //some error occured } else { //your code here } return true; } //$server->setDebugMode(true); $server->addMethod('conversionEndCallback'); $server->processRequest(); ?>
