public void HttpClientService_GetSingleAsync_ReturnsErrorObject_WhenInvalidHttpResponse() { _mockHttpMessageHandler.Setup(f => f.Send(It.IsAny <HttpRequestMessage>())).Returns(new HttpResponseMessage { StatusCode = HttpStatusCode.NotFound, Content = new StringContent("Error encountered during processing") }); IHttpClientService httpClientService = new HttpClientService("http://api.ratings.food.gov.uk", "Establishment", _httpClient); HttpClientResponse <Establishment> response = httpClientService.GetSingleAsync <Establishment>().Result; Assert.NotNull(response); Assert.Equal(404, response.HttpStatusCode); Assert.Contains("Error encountered during processing", response.ErrorMessage); Assert.Null(response.ResponseContent); }
public async Task <Player> GetUser(int userId, int gameId) { HttpClientResponse response = new HttpClientResponse(); await response.Convert(HttpClientRequestService.Get($"users/{userId}")); if (response.Status == System.Net.HttpStatusCode.NotFound) { return(null); } var user = new PlayerJsonService().ToObject(response.ResponseContent); user.InviteKey.GameId = gameId; return(user.ToPlayer()); }
JsonValue GetUserProfile(JsonValue token) { // get the user info API: https://developers.facebook.com/docs/reference/api/user/ JsonValue userProfile = null; using (WebRequest request = new WebRequest( "https://graph.facebook.com/me?access_token=" + HttpUtility.UrlEncode((string)token["access_token"]) + "&fields=picture,first_name,last_name", allowAutoRedirect: true)) { HttpClientResponse response = request.GetResponse(); if (response.StatusCode == 200) { userProfile = response.ReadAsJson(); } } return(userProfile); }
public HttpClientResponse Dispatch(HttpClientRequest request) { HttpClientResponse lResponse = this.TryDispatch(request); if ((Int32)lResponse.HttpCode >= 400) { if (lResponse.HasContentLength) { throw new HttpException(lResponse.ContentString, lResponse); } throw new HttpException(lResponse.Header.ToString(), lResponse); } return(lResponse); }
public string Request(string url, string cmd, Crestron.SimplSharp.Net.Http.RequestType reqtype) { _request.Url.Parse(url); _request.RequestType = reqtype; if (cmd == null) { _request.ContentString = ""; } else { _request.ContentString = cmd; } _response = _client.Dispatch(_request); String jsontext = _response.ContentString; return jsontext; }
// [native] bool HttpClient.TryDownloadAsync(string url, HttpClientOptions options, HttpClientResponse response, HttpClientAsyncCallback callback) private static void TryDownloadAsync(IntPtr info) { NSJSFunctionCallbackInfo arguments = NSJSFunctionCallbackInfo.From(info); bool success = false; if (arguments.Length > 3) { string url = (arguments[0] as NSJSString)?.Value; HttpClientOptions options = HttpClient.object2options(arguments[1] as NSJSObject); NSJSObject response = arguments[2] as NSJSObject; if (options != null && response != null) { NSJSFunction callback = arguments[3] as NSJSFunction; if (callback != null) { callback.CrossThreading = true; } response.CrossThreading = true; bool fillToObject = false; HttpClientResponse responset = HttpClient.object2response(response); success = RESTClient.TryDownloadAsync(url, options, responset, (error, buffer, count) => { NSJSVirtualMachine machine = arguments.VirtualMachine; if (error == HttpClientError.Success && !fillToObject) { fillToObject = true; fill2object(response, responset); } if (callback != null) { bool breakto = false; machine.Join((sender, state) => breakto = ((callback.Call ( NSJSInt32.New(machine, (int)error), NSJSValue.NullMerge(machine, buffer != null && count >= 0 ? NSJSUInt8Array.New(machine, buffer, count) : null) ) as NSJSBoolean)?.Value) == false); if (breakto) { return(false); } } return(count > 0); }); } } arguments.SetReturnValue(success); }
/* * Talking with John from TrackVia this should work in theory, but generating * errors. Need to work with TrackVia to see if this is possible. It would * GREATLY speed up the update process * */ /* * /// <summary> * /// Updates a record in a view accessible to the authenticated user. * /// </summary> * /// <param name="viewId">view identifier in which to update the record</param> * /// <param name="data">enumerable data instance of RecordData</param> * /// <returns>RecordSet of updated records</returns> * /// <exception cref="TrackViaApiException">if the service fails to process this request</exception> * /// <exception cref="TrackviaClientException">if an error occurs outside the service, failing the request</exception> * public RecordSet updateRecords(long viewId, IEnumerable<RecordData> data) * { * string path = String.Format("{0}/openapi/views/{1}/records/0", this._baseUriPath, viewId); * * RecordDataBatch batch = new RecordDataBatch(data); * * string jsonSerializedData = JsonConvert.SerializeObject(batch); * * HttpClientResponse Response = postCommonSharedCode(path, jsonSerializedData); * * RecordSet rsResponse = JsonConvert.DeserializeObject<RecordSet>(Response.Content); * * return rsResponse; * } * */ /// <summary> /// Updates a record in a view accessible to the authenticated user using the typed object. /// </summary> /// <param name="viewId">view identifier in which to update the record</param> /// <param name="recordId">unique record identifier</param> /// <param name="data">instance of an application-defined class, representing the record data</param> /// <returns></returns> /// <exception cref="TrackViaApiException">if the service fails to process this request</exception> /// <exception cref="TrackviaClientException">if an error occurs outside the service, failing the request</exception> public DomainRecord <T> updateRecord <T>(long viewId, long recordId, T data) { string path = String.Format("{0}/openapi/views/{1}/records/{2}", this._baseUriPath, viewId, recordId); DomainRecordDataBatch <T> batch = new DomainRecordDataBatch <T>(new T[] { data }); string jsonSerializedData = JsonConvert.SerializeObject(batch); HttpClientResponse Response = postCommonSharedCode(path, jsonSerializedData); DomainRecordSet <T> recordSet = JsonConvert.DeserializeObject <DomainRecordSet <T> >(Response.Content); DomainRecord <T> record = (recordSet != null && recordSet.Data != null && recordSet.Data.Count == 1) ? new DomainRecord <T>(recordSet.Structure, recordSet.Data[0]) : null; return(record); }
public static bool TestGetWholeStructure() { bool done = false; using (HttpClient client = HttpClient.Create(HostName, Port)) { HttpClientRequest request = new HttpClientRequest(); request.Method = "GET"; request.Path = "/api/structures/0691669P"; request.QueryString["expand"] = "true"; request.Headers["authorization"] = GetHttpBasic(); client.SendRequest(request); HttpClientResponse response = client.GetResponse(); done = (response.StatusCode == 200); } return(done); }
public static bool TestGet10000Logs() { bool done = false; using (HttpClient client = HttpClient.Create(HostName, Port)) { HttpClientRequest request = new HttpClientRequest(); request.Method = "GET"; request.Path = "/api/logs"; request.QueryString["limit"] = "10000"; request.Headers["authorization"] = GetHttpBasic(); client.SendRequest(request); HttpClientResponse response = client.GetResponse(); done = (response.StatusCode == 200); } return(done); }
void OnHttpRead(HttpClientResponse response, long totalRead) { AutoUpdateCfgItem item = m_Items[m_Curr]; long delta = totalRead - response.ReadBytes; if (delta > 0) { double curM = AutoUpdateMgr.Instance.CurDownM; curM += ((double)delta) / ((double)1024 * 1024); AutoUpdateMgr.Instance.CurDownM = curM; item.readBytes += delta; } //item.readBytes = totalRead; if (totalRead >= response.MaxReadBytes) { item.isDone = true; } m_Items[m_Curr] = item; AutoUpdateMgr.Instance.DownloadUpdateToUpdateTxt(item); /* * float currProcess = 0; * if (response.MaxReadBytes > 0) * currProcess = (float)totalRead/(float)response.MaxReadBytes; * CalcDownProcess(currProcess); * AutoUpdateMgr.Instance.DownProcess = currProcess;*/ double cur = AutoUpdateMgr.Instance.CurDownM; double max = AutoUpdateMgr.Instance.TotalDownM; if (max <= float.Epsilon) { AutoUpdateMgr.Instance.DownProcess = 0; } else { AutoUpdateMgr.Instance.DownProcess = (float)(cur / max); } if (totalRead >= response.MaxReadBytes) { StartNextDownload(); } }
public static bool TestStorageServiceCreate() { bool done = false; using (HttpClient client = HttpClient.Create("localhost", 3333)) { HttpClientRequest request = new HttpClientRequest(); request.Method = "POST"; request.Path = "/storage"; JsonValue json = new JsonObject(); json["quota"] = -1; request.Content = new JsonContent(json); client.SendRequest(request); HttpClientResponse response = client.GetResponse(); done = (response.StatusCode == 200); } return(done); }
public static string SetLvl(string settype, ushort setid, string cmdtype, string cmdval) { var setLights = new HttpClient(); setLights.KeepAlive = false; setLights.Accept = "application/json"; HttpClientRequest lightRequest = new HttpClientRequest(); string url = string.Format("http://{0}/api/{1}/{2}/{3}/{4}", HueBridge.BridgeIp, HueBridge.BridgeApi, settype, setid, cmdtype); lightRequest.RequestType = Crestron.SimplSharp.Net.Http.RequestType.Put; lightRequest.Url.Parse(url); lightRequest.ContentString = cmdval; HttpClientResponse lResponse = setLights.Dispatch(lightRequest); String jsontext = lResponse.ContentString; return(jsontext); }
/// <summary> /// sets scene method /// </summary> /// <param name="setid"></param> /// <param name="payload"></param> /// <returns></returns> public static string SetScene(ushort setid, string payload) { var setLights = new HttpClient(); setLights.KeepAlive = false; setLights.Accept = "application/json"; HttpClientRequest lightRequest = new HttpClientRequest(); string url = string.Format("http://{0}/api/{1}/groups/{2}/action", HueBridge.BridgeIp, HueBridge.BridgeApi, setid); lightRequest.RequestType = Crestron.SimplSharp.Net.Http.RequestType.Put; lightRequest.Url.Parse(url); lightRequest.ContentString = payload; HttpClientResponse lResponse = setLights.Dispatch(lightRequest); String jsontext = lResponse.ContentString; return(jsontext); }
private static string Dispatch(string path, bool reqMID, RequestType type) { try { string body = string.Empty; using (HttpClient client = new HttpClient()) { client.Port = p; client.TimeoutEnabled = true; client.Timeout = 25; HttpClientRequest request = new HttpClientRequest(); if (reqMID) { request.Url.Parse(string.Format("http://{0}{1}?uri=server://{2}/com.plexapp.pligins.library/{1}", adr, path, MachineIdentifier, path)); } else { request.Url.Parse(string.Format("http://{0}{1}", adr, path)); } request.Header.AddHeader(new HttpHeader("Accept", "application/json")); request.Header.AddHeader(new HttpHeader("X-Plex-Token", token)); request.RequestType = type; HttpClientResponse response = client.Dispatch(request); body = response.ContentString; response.Dispose(); } return(body); } catch (HttpException h) { ErrorLog.Error("Error dispatching request: {0}", h.Message); return(string.Empty); } catch (Exception e) { ErrorLog.Error("Error dispatching request: {0}", e.Message); return(string.Empty); } }
/// <summary> /// Updates a record in a view accessible to the authenticated user. /// </summary> /// <param name="viewId">view identifier in which to update the record</param> /// <param name="recordId">unique record identifier</param> /// <param name="data">data instance of RecordData</param> /// <returns>Update Record</returns> /// <exception cref="TrackViaApiException">if the service fails to process this request</exception> /// <exception cref="TrackviaClientException">if an error occurs outside the service, failing the request</exception> public Record updateRecord(long viewId, long recordId, RecordData data) { string path = String.Format("{0}/openapi/views/{1}/records/{2}", this._baseUriPath, viewId, recordId); RecordDataBatch batch = new RecordDataBatch(new RecordData[] { data }); string jsonSerializedData = JsonConvert.SerializeObject(batch); HttpClientResponse Response = postCommonSharedCode(path, jsonSerializedData); RecordSet rsResponse = JsonConvert.DeserializeObject <RecordSet>(Response.Content); Record record = (rsResponse != null && rsResponse.Data != null && rsResponse.Data.Count == 1) ? new Record(rsResponse.Structure, rsResponse.Data[0]) : null; return(record); }
public async Task <List <InviteKey> > GetAll(int gameId) { var response = new HttpClientResponse(); response.HasMultipleResults = true; await response.Convert(HttpClientRequestService.GetAll($"games/{gameId}/invite-keys")); List <InviteKey> inviteKeys = new List <InviteKey>(); foreach (InviteKey inviteKey in new InviteKeyJsonService().ToObjects(response.ResponseContent)) { inviteKey.GameId = gameId; inviteKeys.Add(inviteKey); } return(inviteKeys); }
// Get all users that are linked to a game public async Task <List <Player> > GetAll(int gameId) { var usersResponse = new HttpClientResponse() { HasMultipleResults = true, }; await usersResponse.Convert(HttpClientRequestService.GetAll($"games/{gameId}/users-with-role")); var result = new List <Player>(); foreach (var builder in new PlayerJsonService().ToObjects(usersResponse.ResponseContent)) { result.Add(builder.ToPlayer()); } return(result); }
public void HttpClientService_GetSingleAsync_ReturnsDataFromValidHttpResponse() { _mockHttpMessageHandler.Setup(f => f.Send(It.IsAny <HttpRequestMessage>())).Returns(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new ObjectContent <Establishment>(new Establishment { RatingValue = "5", RatingKey = "fhrs_5_en-gb" }, new JsonMediaTypeFormatter()) }); IHttpClientService httpClientService = new HttpClientService("http://api.ratings.food.gov.uk", "Establishment", _httpClient); HttpClientResponse <Establishment> response = httpClientService.GetSingleAsync <Establishment>().Result; Assert.NotNull(response); Assert.Null(response.ErrorMessage); Assert.Equal(200, response.HttpStatusCode); Assert.NotNull(response.ResponseContent); }
// *** Add a method for source logic that takes info from s+ then uses the rmssource method to get the info to pass along // Callback public void OnHTTPClientResponseCallback(HttpClientResponse userobj, HTTP_CALLBACK_ERROR error) { try { if (error != HTTP_CALLBACK_ERROR.COMPLETED) { ErrorLog.Error("HttpGetRequest OnHTTPClientResponseCallback error: " + error.ToString()); } else if (userobj.ContentString.Length > 0) { DataReceived(userobj.ContentString); } } catch (Exception e) { ErrorLog.Error("Exception HttpGetRequest OnHTTPClientResponseCallback: " + e.Message); } }
//# Thumbnail avec OnlyOffice // curl -X POST http://hostname/onlyoffice/ConvertService.ashx // -H "Content-Type: application/json" -d // '{"async": false, "outputtype":"jpg","thumbnail":{"aspect": 0, "width": 64, "height": 64 },"filetype":"docx","url": "http://hostname/api/docs/3180/content"}' public static async Task <string> ConvertAsync(Logger logger, HttpContext c, string fileUrl, OnlyOfficeFileType fileType, OnlyOfficeFileType destFileType) { string resFileUrl = null; var uri = new Uri(new Uri(c.SelfURL()), "/onlyoffice/ConvertService.ashx"); logger.Log(LogLevel.Info, $"OnlyOffice ConvertService URL: {uri}"); using (HttpClient client = await HttpClient.CreateAsync(uri)) { HttpClientRequest request = new HttpClientRequest(); request.Method = "POST"; request.Path = uri.PathAndQuery; request.Headers["accept"] = "application/json"; var jsonContent = new JsonObject { ["key"] = Guid.NewGuid().ToString(), ["async"] = false, ["codePage"] = 65001, ["filetype"] = fileType.ToString(), ["outputtype"] = destFileType.ToString(), ["url"] = fileUrl }; request.Content = jsonContent; logger.Log(LogLevel.Debug, $"OnlyOffice ConvertService send message for file convert (url: {uri.ToString()}). Response: {jsonContent.ToString()}"); await client.SendRequestAsync(request); HttpClientResponse response = await client.GetResponseAsync(); if (response.StatusCode == 200) { var json = await response.ReadAsJsonAsync(); logger.Log(LogLevel.Debug, $"OnlyOffice ConvertService for file convert (url: {uri.ToString()}). Response: {json.ToString()}"); if (json.ContainsKey("fileUrl")) { resFileUrl = json["fileUrl"]; } } else { logger.Log(LogLevel.Error, $"OnlyOffice ERROR while asking for file convert (url: {uri.ToString()}) for file {fileUrl}. Got HTTP {response.StatusCode}"); } } return(resFileUrl); }
public static bool TestGet1MonthBrowserStats() { bool done = false; using (HttpClient client = HttpClient.Create(HostName, Port)) { HttpClientRequest request = new HttpClientRequest(); request.Method = "GET"; request.Path = "/api/browser_logs/stats"; request.QueryString["mode"] = "1MONTH"; request.QueryString["timestamp>"] = "2018-08-31T22:00:00.000Z"; request.QueryString["timestamp<"] = "2018-09-30T22:00:00.000Z"; request.Headers["authorization"] = GetHttpBasic(); client.SendRequest(request); HttpClientResponse response = client.GetResponse(); done = (response.StatusCode == 200); } return(done); }
private void Response(HttpClientResponse response, HTTP_CALLBACK_ERROR error, object request) { if (error == HTTP_CALLBACK_ERROR.COMPLETED) { var responseReceived = response; if (responseReceived.ContentString.Length > 0) { if (ResponseRecived != null) { ResponseRecived(this, new GenericHttpClientEventArgs(responseReceived.ContentString, (request as HttpClientRequest).Url.ToString(), error)); } Debug.Console(2, this, "GenericHttpClient ResponseReceived"); Debug.Console(2, this, "RX:{0}", responseReceived.ContentString); Debug.Console(2, this, "TX:{0}", (request as HttpClientRequest).Url.ToString()); } } }
public async Task CachingTest() { var cacheRegion = "cacheRegion"; var serviceInfo = new CalledServiceInfo { Name = "Service", Id = Guid.NewGuid(), Endpoint = "Endpoint", CircuitBreakerInfo = new CircuitBreakerInfo { ExceptionCount = 1, BreakDuration = TimeSpan.FromMilliseconds(1) }, Timeout = TimeSpan.FromMilliseconds(100) }; var httpClientResponse = new HttpClientResponse { HttpStatusCode = HttpStatusCode.NoContent, Response = "" }; var cache = new CacheMock(); var httpClientWrapper = Substitute.For <IHttpClientWrapper>(); var tokenService = Substitute.For <ITokenService>(); httpClientWrapper.PostAsync(serviceInfo.Endpoint, null, CancellationToken.None).ReturnsForAnyArgs(httpClientResponse); var sut = new CachedService(cache, httpClientWrapper, tokenService); ServiceResponse actual = await sut.CallService(serviceInfo, cacheRegion, CancellationToken.None, null); Assert.AreEqual(ServiceResponseStatus.Success, actual.Status); actual = await sut.CallService(serviceInfo, cacheRegion, CancellationToken.None, null); Assert.AreEqual(ServiceResponseStatus.Success, actual.Status); await httpClientWrapper.ReceivedWithAnyArgs(1).PostAsync(serviceInfo.Endpoint, null, CancellationToken.None); bool semaphoresRemoved = sut.RemoveSemaphores(cacheRegion); Assert.IsTrue(semaphoresRemoved); }
public static bool TestMessageServiceSearch() { bool done = false; using (HttpClient client = HttpClient.Create("localhost", 3333)) { HttpClientRequest request = new HttpClientRequest(); request.Method = "GET"; request.Path = "/message"; request.QueryString["user"] = "******"; client.SendRequest(request); HttpClientResponse response = client.GetResponse(); if (response.StatusCode == 200) { JsonValue json = response.ReadAsJson(); done = (json.Count == 1); } } return(done); }
JObject Request(HttpClient client, string path, string method, int id, string version, params object[] args) { var jsonData = JsonConvert.SerializeObject(new { method, @params = args, id, version, }, Formatting.Indented); var endpointUrl = string.Format("http://{0}/sony/{1}", IpAddress, path); #if DEBUG CrestronConsole.PrintLine("New request to {0} Method = {1}", endpointUrl, method); CrestronConsole.PrintLine(jsonData); #endif HttpClientRequest request = new HttpClientRequest(); request.Url = new UrlParser(endpointUrl); request.RequestType = RequestType.Post; request.Header.AddHeader(new HttpHeader("X-Auth-PSK", PreSharedKey)); request.Header.AddHeader(new HttpHeader("Content-Type", "application/json")); request.ContentString = jsonData; request.KeepAlive = true; #if DEBUG CrestronConsole.Print("Dispatching... "); #endif try { HttpClientResponse response = client.Dispatch(request); #if DEBUG CrestronConsole.PrintLine("Done - Response {0}", response.Code); CrestronConsole.PrintLine(response.ContentString); #endif return(JObject.Parse(response.ContentString)); } catch (Exception e) { #if DEBUG CrestronConsole.PrintLine("Error: {0}", e.Message); #endif ErrorLog.Error("Error in {0}.Request(), {1}", GetType().Name, e.Message); } return(null); }
private void Callback(HttpClientResponse response, HTTP_CALLBACK_ERROR error) { try { if (error != HTTP_CALLBACK_ERROR.COMPLETED) { CloudLog.Warn("Cannot communicate with AvediaServer to discover channels"); return; } if (response.Code != 200) { CloudLog.Error("{0} HttpResponse = {1}", GetType().Name, response.Code); return; } var channels = JToken.Parse(response.ContentString)["channel"].Select(channel => new Channel(_server, channel)) .ToList(); if (channels.Count > 0) { _channels.Clear(); foreach (var channel in channels) { _channels.Add(channel); } OnChannelsUpdated(this); } else { CloudLog.Warn( "AvediaServer returned no channels in API. Existing collection will remain to prevent loss of channel list."); } } catch (Exception e) { CloudLog.Exception(e); } }
/// <summary> /// generic request for lights, groups, scenes returns a JSON string to be parsed /// </summary> /// <param name="infotype"></param> /// <returns></returns> public static void GetBridgeInfo(string infotype) { try { var getLights = new HttpClient(); getLights.KeepAlive = false; getLights.Accept = "application/json"; HttpClientRequest bridgeRequest = new HttpClientRequest(); string url = string.Format("http://{0}/api/{1}/{2}", HueBridge.BridgeIp, HueBridge.BridgeApi, infotype); bridgeRequest.Url.Parse(url); HttpClientResponse lResponse = getLights.Dispatch(bridgeRequest); String jsontext = lResponse.ContentString; OnInfoReceived(infotype, jsontext); //CrestronConsole.PrintLine("getting bridge info: {0}", infotype); } catch (Exception e) { CrestronConsole.PrintLine("Exception: {0}", e); } }
public HttpClientResponse ExecuteRequest(HttpClientRequest request) { HttpClientResponse result = new HttpClientResponse(); var restSharpRequest = PrepareRequest(request); if (restSharpRequest != null) { _client.BaseUrl = request.BaseUri; var restSharpResponse = _client.Execute(restSharpRequest); PrepareResponse(restSharpResponse, result); } else { result.ErrorException = new ArgumentNullException(nameof(restSharpRequest)); } return(result); }
public static bool TestSendmailService() { bool done = false; using (HttpClient client = HttpClient.Create("localhost", 3333)) { HttpClientRequest request = new HttpClientRequest(); request.Method = "POST"; request.Path = "/sendmail"; JsonValue content = new JsonObject(); content["from"] = "*****@*****.**"; content["to"] = "*****@*****.**"; content["subject"] = "Test Sendmail erasme-cloud-cil"; content["body"] = "Test only. Trash me"; request.Content = new JsonContent(content); client.SendRequest(request); HttpClientResponse response = client.GetResponse(); done = (response.StatusCode == 200); } return(done); }
public string callToWeb() { string result = ""; //myClient.Port = port; //result = myClient.Get(IPAddress); //Console.Write("this webpage said: {0}", result); try { myClientRequest.Url.Parse(ipa); myClientResponse = myClient.Dispatch(myClientRequest); result = myClientResponse.ContentString; } catch (Exception e) { CrestronConsole.PrintLine("Something went wrong = {0}", e); } return(result); }