public EnsureSuccessStatusCode ( ) : |
||
return |
private async Task<string> PostRequest(string URL) { System.Diagnostics.Debug.WriteLine("URL:" + URL); Uri requestUri = new Uri(URL); //Add a user-agent header to the GET request. var headers = httpClient.DefaultRequestHeaders; HttpResponseMessage httpResponse = new HttpResponseMessage(); string httpResponseBody = ""; try { //Send the GET request httpResponse = await httpClient.PostAsync(requestUri, null); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); System.Diagnostics.Debug.WriteLine("Response:" + httpResponseBody); return httpResponseBody; } catch (Exception ex) { throw ex; } }
public override Result CreateResult(HttpResponseMessage responseMessage, IContext context) { responseMessage.EnsureSuccessStatusCode(); ProcessEventsUntilStopped(responseMessage, context); return null; }
public static async Task<string> getInfo(string URL) { HttpClient client = new HttpClient(); HttpResponseMessage response = new HttpResponseMessage(); response = await client.GetAsync(URL); response.EnsureSuccessStatusCode(); Response = await response.Content.ReadAsStringAsync(); return Response; }
/// <summary> /// Initializes connection to Hue bridge /// </summary> /// <param name="url"></param> /// <param name="username"></param> public void Initialize(string url, string username) { if (url.LastIndexOf('/') == url.Length - 1) { url = url.Substring(0, url.Length - 1); } //connect to bridge using IP address from config file //assume connected app and username from config file //ping bridge to ensure connectivity _bridgeApiBase = new Uri(string.Format("{0}/api/{1}", url, username)); try { HttpResponseMessage response = new HttpResponseMessage(); // Create a Http Call for Access Token HttpClient client = new HttpClient(); client.BaseAddress = _bridgeApiBase; client.GetAsync(_bridgeApiBase + "/lights").ContinueWith( (getTask) => { if (getTask.IsCanceled) { return; } if (getTask.IsFaulted) { throw getTask.Exception; } response = getTask.Result; response.EnsureSuccessStatusCode(); }).Wait(); string result = response.Content.ReadAsStringAsync().Result.ToString(); this.Lights = new Dictionary<string, Light>(); JToken token = JToken.Parse(result); if (token.Type == JTokenType.Object) { var lightsJSON = (JObject)token; foreach (var prop in lightsJSON.Properties()) { Light newLight = JsonConvert.DeserializeObject<Light>(prop.Value.ToString()); newLight.Id = prop.Name.ToString(); this.Lights.Add(newLight.Name.ToLower(), newLight); } } } catch (Exception ex) { throw new Exception("Error initializing HueManager. Check inner exception for details.", ex); } }
public void EnsureSuccessStatusCode() { HttpResponseMessage message = new HttpResponseMessage (); Assert.AreSame (message, message.EnsureSuccessStatusCode (), "#1"); message = new HttpResponseMessage (HttpStatusCode.BadRequest); message.ReasonPhrase = "test reason"; try { message.EnsureSuccessStatusCode (); Assert.Fail ("#2"); } catch (HttpRequestException e) { Assert.IsTrue (e.Message.Contains ("400 (test reason)"), "#3"); } }
private async Task<bool> EnsureSuccessOrThrow(HttpResponseMessage resp) { if (resp.IsSuccessStatusCode) { return true; } if (resp.StatusCode == HttpStatusCode.BadRequest || resp.StatusCode == HttpStatusCode.InternalServerError) { var msg = await resp.Content.ReadAsStringAsync(); throw new SelfossServerException(msg, null); } resp.EnsureSuccessStatusCode(); return true; }
public async Task<string> Get(string baseURI, string uri, bool authenticate = true) { await CheckAPIResponsiveness(); if (authenticate) { await AddAuthenticationHeader(); } HttpResponseMessage response = new HttpResponseMessage(); Client.BaseAddress = new Uri(baseURI); response = await Client.GetAsync(uri); response.EnsureSuccessStatusCode(); TokenManager.LastRefresh = DateTime.UtcNow; return await response.Content.ReadAsStringAsync(); }
private async Task<string> WebPageToString(string link) { HttpClient httpClient = new HttpClient(); Uri requestUri = new Uri(link); HttpResponseMessage httpResponse = new HttpResponseMessage(); string httpResponseBody = string.Empty; try { httpResponse = await httpClient.GetAsync(requestUri); httpResponse.EnsureSuccessStatusCode(); httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); } catch (Exception ex) { httpResponseBody = string.Format("Error: {0} Message: ", ex.HResult.ToString("X"), ex.Message); } return httpResponseBody; }
/** * Concatenate a Uri with the given parameters. * If uri invokation was succesfull a list with all users for the given eventId and state will be created, * which will be stored in the variable listUser. **/ public async Task<List<MySqlUser>> SelectUserForEvent(string host, int idEvent, string state) { HttpResponseMessage response = new HttpResponseMessage(); Uri uri = new Uri(host + "php/requestUserForEvent.php?idEvent=" + idEvent + "&state=" + state); List<MySqlUser> listUser = null; string responseText; try { response = await client.GetAsync(uri).ConfigureAwait(continueOnCapturedContext:false); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext:false); listUser = createUserFromResponse(responseText); } catch(Exception e) { Console.WriteLine("Error while selecting data from MySQL: " + e.Message); } return listUser; }
public static void PostAsync(string _URL, object _DATA, TConnector.ConnectorOnEventDelegate _onresponse = null, TConnector.ConnectorOnEventDelegate _onerror = null) { var client = new HttpClient(); byte[] bytes; bytes = System.Text.Encoding.ASCII.GetBytes(_DATA.ToString()); HttpContent content = new ByteArrayContent(bytes); client.PostAsync(_URL, content).ContinueWith( (postTask) => { object retval; HttpResponseMessage msg = new HttpResponseMessage(); try { msg = postTask.Result; msg.EnsureSuccessStatusCode(); } catch (Exception ex) { if (_onerror != null) _onerror(ex); return; } Task<Stream> objResponseStreamTask = msg.Content.ReadAsStreamAsync(); Stream objResponseStream = objResponseStreamTask.Result; XmlDocument xmldoc = new XmlDocument(); try { XmlTextReader objXMLReader = new XmlTextReader(objResponseStream); xmldoc.Load(objXMLReader); objXMLReader.Close(); retval = xmldoc; } catch (Exception) { objResponseStream.Position = 0; StreamReader sr = new StreamReader(objResponseStream); retval = sr.ReadToEnd(); } if (_onresponse != null) _onresponse(retval); }); }
/** * Inserts a user with the given parameters and userId = currentHighestId + 1. * You can check if the insert was succesful in the succes variable. **/ public async Task<bool> InsertUser(string host, string name, string role, string password, int number, string position) { HttpResponseMessage response = new HttpResponseMessage(); Uri uri = new Uri(host + "php/insertUser.php" + "?name=" + name + "&role=" + role + "&password=" + password + "&number=" + number + "&position=" + position); string responseText; try { response = await client.GetAsync(uri); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync(); if(dbCommunicator.wasSuccesful(responseText)) { return true; } if(debug) { Console.WriteLine("Insert response: " + responseText); } } catch(Exception e) { Console.WriteLine("Error while selecting data from MySQL: " + e.Message); return false; } return false; }
public async Task<MySqlUser> validateLogin(string host, string username, string password) { HttpResponseMessage response = new HttpResponseMessage(); Uri uri = new Uri(host + "php/validateLogin.php?username=" + username + "&password=" + password); if(debug) Console.WriteLine("Login uri: " + uri); MySqlUser user = null; string responseText; try { response = await client.GetAsync(uri).ConfigureAwait(continueOnCapturedContext:false); Console.WriteLine("selectuser - response statuscode = " + response.StatusCode); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext:false); user = createUserFromResponse(responseText)[0]; if(debug) Console.WriteLine("Login response: " + responseText); } catch(Exception e) { Console.WriteLine("Error while loging in: " + e.Message + " Source: " + e.InnerException + " | " + e.StackTrace); } return user; }
/** * Delets a user with the given userId. * You can check if the insert was succesful in the succes variable. **/ public async Task<bool> DeleteUser(string host, int idUser) { HttpResponseMessage response = new HttpResponseMessage(); Uri uri = new Uri(host + "php/deleteUser.php" + "?idUser=" + idUser); string responseText; try { response = await client.GetAsync(uri); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync(); if(dbCommunicator.wasSuccesful(responseText)) { return true; } if(debug) { Console.WriteLine("Delete response: " + responseText); } } catch(Exception e) { Console.WriteLine("Error while selecting data from MySQL: " + e.Message); return false; } return false; }
void EnsureSuccessStatusCode(HttpResponseMessage m) { if (m.StatusCode == HttpStatusCode.Forbidden) { throw new HttpForbiddenException(); } if (m.StatusCode == HttpStatusCode.GatewayTimeout) { throw new HttpConnectionException(); } if (m.StatusCode == HttpStatusCode.NotFound) { throw new HttpNotFoundException(); } m.EnsureSuccessStatusCode(); }
public static void PrintResponse(HttpResponseMessage response) { response.EnsureSuccessStatusCode(); Console.WriteLine("Response:"); Console.WriteLine(response); if (response.Content != null) { Console.WriteLine(response.Content.ReadAsStringAsync().Result); } }
private async Task ThrowOnError(HttpResponseMessage response) { if (response.StatusCode == HttpStatusCode.BadRequest) { var content = await response.Content.ReadAsStringAsync(); var errorResponse = JsonConvert.DeserializeObject<ErrorResponse>(content); throw new BadRequestException("KairosDb returned status code 400: Bad Request.", errorResponse.Errors); } response.EnsureSuccessStatusCode(); }
public async void getPublicNews() { //string phpAddress = "http://localhost/NewsReaderExpress/viewNewsPost.php"; string phpAddress = "http://localhost:21750/NewsReaderExpressPHP/viewNewsPost.php"; httpClient = new HttpClient(); // Add a user-agent header var headers = httpClient.DefaultRequestHeaders; // HttpProductInfoHeaderValueCollection is a collection of // HttpProductInfoHeaderValue items used for the user-agent header headers.UserAgent.ParseAdd("ie"); headers.UserAgent.ParseAdd("Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); response = new HttpResponseMessage(); Uri resourceUri; if (!Uri.TryCreate(phpAddress.Trim(), UriKind.Absolute, out resourceUri)) { return; } if (resourceUri.Scheme != "http" && resourceUri.Scheme != "https") { return; } // ---------- end of test--------------------------------------------------------------------- string responseText; try { response = await httpClient.GetAsync(resourceUri); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { // Need to convert int HResult to hex string responseText = "Error = " + ex.HResult.ToString("X") + " Message: " + ex.Message; return; } string jsonString = responseText.ToString(); newsItems = DataElements(jsonString); SharedInformation share = SharedInformation.getInstance(); share.setNewsData(newsItems); }
private async Task UpdateLoginHeaderInformation( HttpResponseMessage response) { response.EnsureSuccessStatusCode(); var getHtmlTask = response.Content.ReadAsStringAsync(); var wbat = response.Headers.GetValues("wbat").First(); this.Client.LoginHeader["wbat"] = wbat; var token = ParseLoginToken(await getHtmlTask); this.Client.LoginHeader["url_login_token"] = token; this.UrlEncodedContent = new FormUrlEncodedContent(this.Client.LoginHeader.Values); }
private async Task UpdateScheduledTimesList( HttpResponseMessage response) { response.EnsureSuccessStatusCode(); var shifts = await GetShiftStringsAsync(this.Client); var list = ScheduledTimeList.Parse(shifts, StartRegexFormat, EndRegexFormat, Sync); list.Sort((a, b) => a.Start.CompareTo(b.Start)); this.Content = list; }
private async void Save(object sender, RoutedEventArgs e) { phpAddress = "http://localhost/NewsReaderExpress/insNewsPost.php"; //?headLine=" + headLine.Text + "&type=" + rb.Content + "&details=" + details.Text + "&fileName=" + fileName; phpAddress = "http://localhost:21750/NewsReaderExpressPHP/insNewsPost.php"; response = new HttpResponseMessage(); byte[] image = PhotoStreamToBase64(); Uri resourceUri; if (!Uri.TryCreate(phpAddress.Trim(), UriKind.Absolute, out resourceUri)) { phpStatus.Text = "Invalid URI, please re-enter a valid URI"; return; } if (resourceUri.Scheme != "http" && resourceUri.Scheme != "https") { phpStatus.Text = "Only 'http' and 'https' schemes supported. Please re-enter URI"; return; } // ---------- end of test--------------------------------------------------------------------- string responseText; phpStatus.Text = "Waiting for response ..."; try { MultipartFormDataContent content = new MultipartFormDataContent(); content.Add((new StringContent(headLine.Text, System.Text.Encoding.UTF8, "text/plain")), "headLine"); content.Add((new StringContent((string)rb.Content, System.Text.Encoding.UTF8, "text/plain")), "type"); content.Add((new StringContent(details.Text, System.Text.Encoding.UTF8, "text/plain")), "details"); content.Add((new StringContent(fileName, System.Text.Encoding.UTF8, "text/plain")), "fileName"); //Uploading the image var imageContent = new ByteArrayContent(image); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); content.Add(imageContent, "image", headLine.Text+".jpg"); /***********/ response = await httpClient.PostAsync(resourceUri, content); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { // Need to convert int HResult to hex string phpStatus.Text = "Error = " + ex.HResult.ToString("X") + " Message: " + ex.Message; responseText = ""; } phpStatus.Text = response.StatusCode + " " + response.ReasonPhrase; // now 'responseText' contains the response as a verified text. // next 'responseText' is displayed phpStatus.Text = responseText.ToString(); //DataSource update= DataSource.returnInstance(); //update.updateNews(phpAddress2); NavigationService.Navigate(new Uri("/PanoramaPage1.xaml", UriKind.RelativeOrAbsolute)); }
/// <summary> /// Handles processing a response from the server /// </summary> /// <param name="response">HttpResponseMessage from the server</param> /// <returns>Task<string></returns> /// <exception cref="System.Security.Authentication.InvalidCredentialException">Thrown when an invalid username or password is supplied.</exception> /// <exception cref="CiresonPortalAPI.CiresonApiException">Thrown when an internal server error (HTTP 500) occurs.</exception> /// <exception cref="System.Net.Http.HttpRequestException">Thrown when any other HTTP exception occurs.</exception> private async Task<string> ProcessResponse(HttpResponseMessage response) { string result = string.Empty; if (response.IsSuccessStatusCode) { result = await response.Content.ReadAsStringAsync(); } else if (response.StatusCode == HttpStatusCode.Unauthorized || response.StatusCode == HttpStatusCode.Forbidden) { throw new InvalidCredentialException("Invalid username or password."); } else if (response.StatusCode == HttpStatusCode.InternalServerError) { // Get the error message from the server result = await response.Content.ReadAsStringAsync(); throw new CiresonApiException(result); } else { // Other unhandled errors try { response.EnsureSuccessStatusCode(); } catch (HttpRequestException) { // Rethrow exception throw; } } return result; }
private static async Task HandleErrorResponse(HttpResponseMessage response) { if (response.IsSuccessStatusCode) { return; } // In case of errors, the response should contain additional textual information // formatted as key=value pairs separated by the \n character. if (response.Content != null) { var mediaType = response.Content.Headers?.ContentType?.MediaType; if (string.Equals(mediaType, "text/plain")) { var textResponseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var detailsToInclude = textResponseBody?.Split('\n') .Select(s => s.Trim()) .Where(s => s.Length > 0) .Where(v => ErrorResponseKeysToIncludeInExceptionDetails.Any(key => v.StartsWith(key, StringComparison.OrdinalIgnoreCase))) .ToList(); if (detailsToInclude?.Count > 0) { throw new Exception( $"Received error response from SMS connector ({(int) response.StatusCode} {response.ReasonPhrase}). {string.Join("; ", detailsToInclude)}"); } } } response.EnsureSuccessStatusCode(); }
private static void EnsureSuccessStatusCode(HttpResponseMessage response) { if ((int)response.StatusCode < 100) { response.StatusCode = HttpStatusCode.OK; response.ReasonPhrase = "OK"; } string contentTypeMediaType = response.Content?.Headers?.ContentType?.MediaType; bool isNotCCPWithXmlContent = response.RequestMessage.RequestUri.Host != APIProvider.DefaultProvider.Url.Host && response.RequestMessage.RequestUri.Host != APIProvider.TestProvider.Url.Host && contentTypeMediaType != null && !contentTypeMediaType.Contains("xml"); if (isNotCCPWithXmlContent || response.Content?.Headers?.ContentLength == 0) response.EnsureSuccessStatusCode(); }
private static async Task<ProcessorRuntimeStatus[]> GetHttpResponseAsRuntimeStatusAsync(HttpResponseMessage response) { response.EnsureSuccessStatusCode(); string sJson = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<ProcessorRuntimeStatus[]>(sJson); }
/// <summary> /// Posts a API command for a single light to the Hue Bridge. Used to change the State of a light. /// </summary> /// <param name="light"></param> /// <param name="command"></param> private void SendApiCommand(Light light, string command) { try { HttpResponseMessage response = new HttpResponseMessage(); // Create a Http Call for Access Token HttpClient client = new HttpClient(); client.BaseAddress = _bridgeApiBase; client.PutAsync(_bridgeApiBase + "/lights/" + light.Id.ToString() + "/state", new StringContent(command)).ContinueWith( (getTask) => { if (getTask.IsCanceled) { return; } if (getTask.IsFaulted) { throw getTask.Exception; } response = getTask.Result; response.EnsureSuccessStatusCode(); }).Wait(); string result = response.Content.ReadAsStringAsync().Result.ToString(); } catch (Exception ex) { throw new Exception("Error sending command. Check inner exception for details.", ex); } }
/// <summary> /// Asynchronously processes an HTTP response message, ensuring it was successful and extracting its content. /// </summary> private static async Task<HttpResponse> ProcessResponseAsync( HttpResponseMessage response, Encoding encoding ) { // HACK: If it's a redirect, just return an empty response, we're interested in the cookies if ( (int) response.StatusCode / 100 == 3 ) { return new HttpResponse( "", "" ); } response.EnsureSuccessStatusCode(); byte[] bytes = await response.Content.ReadAsByteArrayAsync(); string content = encoding.GetString( bytes, 0, bytes.Length ); string requestUrl = response.RequestMessage.RequestUri.ToString(); return new HttpResponse( content, requestUrl ); }
public virtual void EnsureSuccess(HttpResponseMessage response) { response.EnsureSuccessStatusCode(); }
public async Task<string> Put(string uri, String rawJSON) { await CheckAPIResponsiveness(); await AddAuthenticationHeader(); string returnString = ""; Client.BaseAddress = new Uri(StringConstants.APIMemberURL); var contentPost = new StringContent(rawJSON, Encoding.UTF8, "application/json"); HttpResponseMessage response = new HttpResponseMessage ();; response = await Client.PutAsync(uri, contentPost); returnString = response.Content.ReadAsStringAsync().Result; if (returnString.Contains ("422")) { var objectJ = JObject.Parse(returnString); // parse as array string description = (String)objectJ ["Message"]; var exception = new Exception (description); throw exception; } else { response.EnsureSuccessStatusCode(); } TokenManager.LastRefresh = DateTime.UtcNow; return returnString; }
private static async Task EnsureSuccessStatusCode (HttpResponseMessage response) { if (!response.IsSuccessStatusCode) { string responseMessage = null; try { using (var responseStream = await response.Content.ReadAsStreamAsync()) { using (var reader = new StreamReader (responseStream, Encoding.UTF8)) { responseMessage = reader.ReadToEnd(); } } } catch (Exception x) { s_logger.Error ("Exception while trying to read the error message.", x); // throw default exception, if reading the response fails response.EnsureSuccessStatusCode(); } throw new HttpRequestException ( string.Format ( "Response status code does not indicate success: '{0}' ('{1}'). Message:\r\n{2}", (int) response.StatusCode, response.StatusCode, responseMessage)); } }
private async void connectHttp(string address, string UserID, string EmployeeName, string SupervisorID, string Location, string Reason, string CheckType) { response = new HttpResponseMessage(); string responseText; Uri resourceUri; if (!Uri.TryCreate(address.Trim(), UriKind.Absolute, out resourceUri)) { //return "Invalid URI, please re-enter a valid URI"; return; } if (resourceUri.Scheme != "http" && resourceUri.Scheme != "https") { //return "Only 'http' and 'https' schemes supported. Please re-enter URI"; return; } // ---------- end of test--------------------------------------------------------------------- try { MultipartFormDataContent content = new MultipartFormDataContent(); content.Add((new StringContent(UserID, System.Text.Encoding.UTF8, "text/plain")), "UserID"); content.Add((new StringContent(EmployeeName, System.Text.Encoding.UTF8, "text/plain")), "EmployeeName"); content.Add((new StringContent(SupervisorID, System.Text.Encoding.UTF8, "text/plain")), "SupervisorID"); content.Add((new StringContent(Location, System.Text.Encoding.UTF8, "text/plain")), "Location"); content.Add((new StringContent(Reason, System.Text.Encoding.UTF8, "text/plain")), "Reason"); content.Add((new StringContent(CheckType, System.Text.Encoding.UTF8, "text/plain")), "CheckType"); response = await httpClient.PostAsync(resourceUri, content); response.EnsureSuccessStatusCode(); responseText = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { // Need to convert int HResult to hex string //Result.Text = "Error = " + ex.HResult.ToString("X") + // " Message: " + ex.Message; responseText = ""; } }