Sample Code
The following code is in C#. It gives an idea on how to use the WebRequest class of .Net with the API.
Use this code as a basis for your developments. However keep in mind:
- The sample code does basic error handling only. For example you would need to intercept exceptions systematically.
- The sample code is all synchronous. If you are calling the API on a UI thread you should switch to asynchronous approaches (while still using the WebRequest class).
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.IO.Compression; using System.Net; using Newtonsoft.Json.Linq; namespace UnitTestProject1 { /// <summary> /// Sample proxy class to use the API. /// /// Please note: /// /// - This class only implements very basic error handling. /// In production code, full error handling needs to be implemented. /// /// - API calls running in a UI should be better implemented using asynchronous web calls. /// /// </summary> public class ApiProxy { // The API end point private string mApiUrl; /// <summary> /// Constructor /// </summary> /// <param name="apiurl"></param> public ApiProxy(string apiurl) { mApiUrl = apiurl; } /// <summary> /// Connect and get token. /// Throws exception if anything fails. /// </summary> /// <param name="domain"></param> /// <param name="ui"></param> /// <returns></returns> public string Connect(string account, string login, string pwd, string domain, string ui) { // Parameters UriBuilderExt ub = new UriBuilderExt(string.Format("{0}/api/connect", mApiUrl)); ub.AddParameter("account", account); ub.AddParameter("login", login); ub.AddParameter("pwd", pwd); ub.AddParameter("domain", domain); ub.AddParameter("ui", ui); // Create request var request = WebRequest.Create(ub.Uri); request.Method = "GET"; // Submit bool error; JObject json = GetJsonResult(request, out error); // If there is an error, we should handle it better than this: if (error) throw new Exception(json.ToString()); // Ok let's get the session token return (string)json["token"]; } /// <summary> /// Connect and get token. /// Throws exception if anything fails. /// </summary> /// <param name="domain"></param> /// <param name="ui"></param> /// <returns></returns> public void Disconnect(string token) { // Parameters UriBuilderExt ub = new UriBuilderExt(string.Format("{0}/api/disconnect", mApiUrl)); ub.AddParameter("token", token); // Create request var request = WebRequest.Create(ub.Uri); request.Method = "PUT"; request.ContentType = "application/json"; request.ContentLength = 0; using (WebResponse response = request.GetResponse()) { var status = ((HttpWebResponse)response).StatusCode; } } /// <summary> /// Connect and get token. /// Throws exception if anything fails. /// </summary> /// <param name="domain"></param> /// <param name="ui"></param> /// <returns></returns> public JObject GetConfiguration(string token, int option) { // Parameters UriBuilderExt ub = new UriBuilderExt(string.Format("{0}/api/it/configuration", mApiUrl)); ub.AddParameter("token", token); ub.AddParameter("option", option.ToString()); var request = WebRequest.Create(ub.Uri); request.Method = "GET"; // Submit bool error; JObject json = GetJsonResult(request, out error); if (error) throw new Exception(json.ToString()); return json; } /// <summary> /// Connect and get token. /// Throws exception if anything fails. /// </summary> /// <param name="domain"></param> /// <param name="ui"></param> /// <returns></returns> public int SubmitRequest(string token, string filepath, string src, string trg, int option, int foption) { // Parameters UriBuilderExt ub = new UriBuilderExt(string.Format("{0}/api/it/requests", mApiUrl)); ub.AddParameter("token", token); ub.AddParameter("filename", Path.GetFileName(filepath)); ub.AddParameter("src", src); ub.AddParameter("trg", trg); ub.AddParameter("option", option.ToString()); ub.AddParameter("foption", foption.ToString()); // Create request var request = WebRequest.Create(ub.Uri); request.Method = "POST"; request.ContentType = "stream"; request.Timeout = 1000 * 360; // 1 sec * 100 // Upload file using (Stream requeststream = request.GetRequestStream()) { using (Stream filestream = File.OpenRead(filepath)) { using (DeflateStream dstream = new DeflateStream(requeststream, CompressionMode.Compress, true)) { filestream.CopyTo(dstream); } } } // Get response bool error; JObject result = GetJsonResult(request, out error); if (error) throw new Exception(); int id = (int)result["id"]; return id; } /// <summary> /// Connect and get token. /// Throws exception if anything fails. /// </summary> /// <param name="domain"></param> /// <param name="ui"></param> /// <returns></returns> public string DownloadTranslation(string token, int requestId) { // Parameters UriBuilderExt ub = new UriBuilderExt(string.Format("{0}/api/it/requests/file", mApiUrl)); ub.AddParameter("token", token); ub.AddParameter("id", requestId.ToString()); // Create request var request = WebRequest.Create(ub.Uri); request.Method = "GET"; // Get file return DownloadTranslation(request); } /// <summary> /// Connect and get token. /// Throws exception if anything fails. /// </summary> /// <param name="domain"></param> /// <param name="ui"></param> /// <returns></returns> public void SubmitPostEditRequest(string token, List<int> ids) { // Parameters UriBuilderExt ub = new UriBuilderExt(string.Format("{0}/api/it/requests/postedit", mApiUrl)); ub.AddParameter("token", token); ub.AddParameter("ids", string.Join(",", ids)); ub.AddParameter("reference", "My reference"); ub.AddParameter("deadline", DateTime.UtcNow.AddDays(1).ToString("o")); ub.AddParameter("comments", ""); // Create request var request = WebRequest.Create(ub.Uri); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = 0; using (WebResponse response = request.GetResponse()) { var status = ((HttpWebResponse)response).StatusCode; } } /// <summary> /// Connect and get token. /// Throws exception if anything fails. /// </summary> /// <param name="domain"></param> /// <param name="ui"></param> /// <returns></returns> public string DownloadPostEdit(string token, int requestId) { // Parameters UriBuilderExt ub = new UriBuilderExt(string.Format("{0}/api/it/requests/postedit/file", mApiUrl)); ub.AddParameter("token", token); ub.AddParameter("id", requestId.ToString()); // Create request var request = WebRequest.Create(ub.Uri); request.Method = "GET"; request.ContentType = "application/json"; request.ContentLength = 0; // Get file return DownloadTranslation(request); } /// <summary> /// Generic method to download a gzip compressed file. /// </summary> /// <param name="response"></param> /// <returns></returns> private string DownloadTranslation(WebRequest request) { WebResponse response = null; try { // Get the response. // In case we have an error status 400 from Beebox we get an exception. try { response = request.GetResponse(); } catch (WebException ex) { // Handle API originating errors (HTTP error = 400) containing a JSON if (ex.Response is HttpWebResponse && (ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.BadRequest) { using (var stream = ex.Response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { JObject jerror = JObject.Parse(reader.ReadToEnd()); throw new Exception("Oups: " + jerror.ToString()); } } } // Something else, we rethrow throw; } // Make sure we have OK status var status = ((HttpWebResponse)response).StatusCode; if (status != HttpStatusCode.OK) throw new Exception("Oups!"); // Download file string temppath = null; try { using (var stream = response.GetResponseStream()) { // Decompress using (DeflateStream dfstream = new DeflateStream(stream, CompressionMode.Decompress, true)) { temppath = Path.GetTempFileName(); using (Stream targetstream = File.OpenWrite(temppath)) { dfstream.CopyTo(targetstream); } } } return temppath; } catch { // In case of error we delete the temp file if (temppath != null) File.Delete(temppath); throw; } } finally { if (response != null) response.Dispose(); } } /// <summary> /// Gets JSON result **synchronously**. /// If HTTP result status is neither 200 nor 400, an exception is raised. /// </summary> /// <param name="request">The web request</param> /// <param name="error"> /// False: Json is the success result. /// True: Json is the API error result which contains the error message etc. /// </param> /// <returns>JSON</returns> private JObject GetJsonResult(WebRequest request, out bool error) { WebResponse response = null; try { // Get the response. // In case we have an error status 400 from Beebox we get an exception. try { response = request.GetResponse(); } catch (WebException ex) { // Handle API originating errors (HTTP error = 400) containing a JSON if (ex.Response is HttpWebResponse && (ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.BadRequest) { using (var stream = ex.Response.GetResponseStream()) { using (var reader = new StreamReader(stream)) { JObject jerror = JObject.Parse(reader.ReadToEnd()); throw new Exception("Oups: " + jerror.ToString()); } } } // Something else, we rethrow throw; } var status = ((HttpWebResponse)response).StatusCode; if (status == HttpStatusCode.BadRequest || status == HttpStatusCode.OK) { // If 200 or 400 we have JSON! using (var stream = response.GetResponseStream()) { var eresult = (new StreamReader(stream)).ReadToEnd(); JObject jerror = JObject.Parse(eresult); error = status == HttpStatusCode.BadRequest; return jerror; } } else { // A different error, we do not get JSON here // Might want to read the contents too for logging etc. throw new Exception(status.ToString()); } } finally { if (response != null) response.Dispose(); } } } /// <summary> /// Helper class to add query parameters to an URI /// </summary> public class UriBuilderExt { private NameValueCollection collection; private UriBuilder builder; public UriBuilderExt(string uri) { builder = new UriBuilder(uri); collection = System.Web.HttpUtility.ParseQueryString(string.Empty); } public void AddParameter(string key, string value) { collection.Add(key, value); } public Uri Uri { get { builder.Query = collection.ToString(); return builder.Uri; } } } }
Copyright Wordbee - Buzzin' Outside the Box since 2008