public async Task<string> PutJsonAsync(string url, IHttpContent content, string token = null) { HttpClient client = new HttpClient(); client.DefaultRequestHeaders .Accept .Add(new HttpMediaTypeWithQualityHeaderValue("application/json")); if (token != null) { client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); } HttpResponseMessage response = await client.PutAsync(new Uri(BaseUrl + url), content); string result = await response.Content.ReadAsStringAsync(); return result; }
/// <summary> /// Invoked to acquire the PlayReady license. /// </summary> /// <param name="licenseServerUri">License Server URI to retrieve the PlayReady license.</param> /// <param name="httpRequestContent">HttpContent including the Challenge transmitted to the PlayReady server.</param> public async virtual Task<IHttpContent> AcquireLicense(Uri licenseServerUri, IHttpContent httpRequestContent) { try { HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Add("msprdrm_server_redirect_compat", "false"); httpClient.DefaultRequestHeaders.Add("msprdrm_server_exception_compat", "false"); HttpResponseMessage response = await httpClient.PostAsync(licenseServerUri, httpRequestContent); response.EnsureSuccessStatusCode(); if (response.StatusCode == HttpStatusCode.Ok) { _lastErrorMessage = string.Empty; return response.Content; } else { _lastErrorMessage = "AcquireLicense - Http Response Status Code: " + response.StatusCode.ToString(); } } catch (Exception exception) { _lastErrorMessage = exception.Message; return null; } return null; }
internal static async Task<string> UploadString(string url, Dictionary<string, string> headers,IHttpContent content, string method = "post") { var client = GetHttpClient(); if (headers != null && headers.Count > 0) { foreach (var pair in headers) { client.DefaultRequestHeaders.Add(pair.Key, pair.Value); } } HttpResponseMessage response; switch (method.ToLower()) { case "put": response = await client.PutAsync(new Uri(url), content); break; case "delete": response = await client.DeleteAsync(new Uri(url)); break; default: response = await client.PostAsync(new Uri(url), content); break; } var result = await response.Content.ReadAsStringAsync(); return result; }
public Response(string stringurl, IHttpContent content) { url = stringurl; cont = content; post = true; }
/// <summary> /// Initializes a new instance of the <see cref="DefaultHttpResponseMessage"/> class. /// </summary> /// <param name="requestMessage">The request message for this response</param> /// <param name="responseMessage">The response message to wrap</param> /// <param name="exception">The exception that occurred during the request</param> public DefaultHttpResponseMessage([NotNull] IHttpRequestMessage requestMessage, [NotNull] HttpWebResponse responseMessage, [CanBeNull] WebException exception = null) { ResponseMessage = responseMessage; _exception = exception; _requestMessage = requestMessage; var responseHeaders = new GenericHttpHeaders(); var contentHeaders = new GenericHttpHeaders(); if (responseMessage.SupportsHeaders) { foreach (var headerName in responseMessage.Headers.AllKeys) { IHttpHeaders headers; if (headerName.StartsWith("Content-", StringComparison.OrdinalIgnoreCase)) { headers = contentHeaders; } else { headers = responseHeaders; } headers.TryAddWithoutValidation(headerName, responseMessage.Headers[headerName]); } } _content = new HttpWebResponseContent(contentHeaders, responseMessage); _responseHttpHeaders = responseHeaders; }
/// <summary> /// Initializes a new instance of the <see cref="DefaultHttpResponseMessage"/> class. /// </summary> /// <param name="responseMessage">The response message to wrap</param> public DefaultHttpResponseMessage([NotNull] HttpResponseMessage responseMessage) { ResponseMessage = responseMessage; if (responseMessage.RequestMessage != null) _requestMessage = new DefaultHttpRequestMessage(responseMessage.RequestMessage); _content = responseMessage.Content.AsRestHttpContent(); _responseHttpHeaders = new DefaultHttpHeaders(responseMessage.Headers); }
private static async Task<HttpResponseMessage> Put (Uri uri, IHttpContent httpContent, List<KeyValuePair<string, string>> headerParameters = null) { var httpClient = CreateHttpClient(headerParameters); try { var response = await httpClient.PutAsync(uri, httpContent); return response; } catch (Exception exception) { throw new Exception(exception.ToString(), exception); } finally { httpClient.Dispose(); } }
/// <summary> /// Initializes a new instance of the <see cref="ContentResult"/> class. /// </summary> /// <param name="content">The body content.</param> /// <param name="contentType">The content type header.</param> public ContentResult(IHttpContent content, HttpMediaTypeHeaderValue contentType) { if (content == null) { throw new NullReferenceException("content"); } if (contentType == null) { throw new ArgumentException("contentType"); } Content = content; ContentType = contentType; }
public static async Task<EditResponse> ParseEditResponseAsync(IHttpContent response) { string json = await response.ReadAsStringAsync(); var jsonObject = JsonObject.Parse(json); int errorCode = (int)jsonObject["status"].GetNumber(); string newToken = jsonObject["new_token"].GetString(); string url = jsonObject["url"].GetString(); string expiration = jsonObject["expiration"].GetString(); return new EditResponse { ErrorCode = errorCode, Token = newToken, Url = url, Expiration = new FileExpiration(expiration) }; }
public static async Task<UploadResponse> ParseUploadResponseAsync(IHttpContent response) { string json = await response.ReadAsStringAsync(); var jsonObject = JsonObject.Parse(json); string token = jsonObject["data"].GetObject()["token"].GetString(); string secureId = jsonObject["data"].GetObject()["secure_id"].GetString(); int errorCode = (int)jsonObject["err"].GetNumber(); string expiration = jsonObject["expiration"].GetString(); return new UploadResponse { Token = token, ErrorCode = errorCode, Expiration = new FileExpiration(expiration), SecureId = secureId }; }
public RequestBuilder(string httpMethod, string[] headersToParse, string baseUri, string relativeUri, bool hasBody, bool isFormEncoded, bool isMultipart) { Request = new HttpRequestMessage(); Request.Method = new HttpMethod(httpMethod); ParseHeaders(headersToParse); BaseUri = baseUri; RelativeUri = relativeUri; HasBody = hasBody; if (IsFormEncoded = isFormEncoded) { Fields = new List<KeyValuePair<string, string>>(); } else if (IsMultipart = isMultipart) { Form = new HttpMultipartFormDataContent(); } }
public static async Task<HttpResponseMessage> PatchAsync(this HttpClient client, Uri requestUri, IHttpContent iContent) { var method = new HttpMethod("PATCH"); var request = new HttpRequestMessage(method, requestUri) { Content = iContent }; HttpResponseMessage response = new HttpResponseMessage(); try { response = await client.SendRequestAsync(request); } catch (TaskCanceledException e) { Debug.WriteLine("ERROR: " + e.ToString()); } return response; }
public async Task doActualResponse(string url, IHttpContent cont, bool post) { client = API.getAPI().getClient(); notLoggedIn = true; pageCouldNotBeFound = true; somethingWentWrong = true; if (testInternet()) { return; } if (await getResponse(url, cont, post)) { return; } if (page.Contains("Forgot your password?")) { return; } notLoggedIn = false; somethingWentWrong = false; }
/// <summary> /// Initializes a new instance of the <see cref="DefaultHttpRequestMessage"/> class. /// </summary> /// <param name="requestMessage">The request message to wrap</param> public DefaultHttpRequestMessage([NotNull] HttpRequestMessage requestMessage) { RequestMessage = requestMessage; _requestHttpHeaders = new DefaultHttpHeaders(requestMessage.Headers); _content = requestMessage.Content.AsRestHttpContent(); }
/// <summary>Add HTTP content to a collection of <see cref="T:System.Net.Http.HttpContent" /> objects that get serialized to multipart/form-data MIME type.</summary> /// <param name="content">The HTTP content to add to the collection.</param> /// <param name="name">The name for the HTTP content to add.</param> /// <param name="fileName">The file name for the HTTP content to add to the collection.</param> /// <exception cref="T:System.ArgumentException">The <paramref name="name" /> was null or contains only white space characters.-or-The <paramref name="fileName" /> was null or contains only white space characters.</exception> /// <exception cref="T:System.ArgumentNullException">The <paramref name="content" /> was null.</exception> public void Add(IHttpContent content, string name, string fileName) { _content.Add(content.ToImplementation(), name, fileName); }
//Send post request with timeout internal static async Task <HttpResponseMessage> SendPostRequestAsync(Int32 TimeOut, string UserAgent, string[][] RequestHeader, Uri PostUrl, IHttpContent PostContent) { try { using (HttpBaseProtocolFilter ProtocolFilter = new HttpBaseProtocolFilter()) { ProtocolFilter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache; using (HttpClient httpClient = new HttpClient(ProtocolFilter)) { httpClient.DefaultRequestHeaders.Add("User-Agent", UserAgent); httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache, no-store"); if (RequestHeader != null) { foreach (String[] StringArray in RequestHeader) { httpClient.DefaultRequestHeaders.Add(StringArray[0], StringArray[1]); } } using (CancellationTokenSource CancelToken = new CancellationTokenSource()) { CancelToken.CancelAfter(TimeOut); IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> HttpConnectAsync = httpClient.PostAsync(PostUrl, PostContent); HttpResponseMessage ConnectTask = await HttpConnectAsync.AsTask(CancelToken.Token); Debug.WriteLine("SendPostRequestAsync succeeded for url: " + PostUrl); return(ConnectTask); } } } } catch (Exception e) { Debug.WriteLine("SendPostRequestAsync exception for url: " + PostUrl + " HRESULT 0x" + e.HResult.ToString("x")); return(null); } }
public void Dispose() { _content = null; _httpResponseMessage.Dispose(); }
protected void SetContentHeaders(IHttpContent content) { _request.ContentLength = content.GetContentLength(); _request.ContentType = content.GetContentType(); }
public Response(string url) { this.url = url; cont = null; post = true; }
public HttpRequestMessage GetRequest() { if (IsFormEncoded) { Form = new HttpFormUrlEncodedContent(Fields); } Request.RequestUri = new Uri(BaseUri + RelativeUri); Request.Content = Form; return Request; }
private async Task<Response> getResponse(string url, IHttpContent cont) { return await getResponse(url, cont, true); }
public async static Task <HttpResponseMessage> OptionsAsync(this HttpClient client, string requestUri, IHttpContent content) { return(await OptionsAsync(client, new Uri(requestUri), content).ConfigureAwait(false)); }
public virtual void messageReceived(IChannelHandlerContext ctx, object msg) { lock (this) { IChannel ch = ctx.Channel; if (this.Interrupted) { if (!(msg is ILastHttpContent)) { log.Info("Force socket close [" + ch.Id + "]"); closeChannel(ch); } } if (msg is IHttpResponse) { if (this.isNot(OPEN)) { errorAsync(ch); return; } this.set(OCCUPIED); IHttpResponse response = (IHttpResponse)msg; int respCode = response.Status.Code; if (respCode < 200) { //100 family, not expected errorAsync(ch); return; } else if (respCode < 300) { //200 family: all is good } else if (respCode < 400) { //300 family: TODO 1.1 handling redirections log.Warn("Redirection currently not implemented"); //String target = response.headers().get(HttpHeaderNames.LOCATION) errorAsync(ch); return; } else { //400 - 500 families: problems errorAsync(ch); return; } keepalive = HttpUtil.IsKeepAlive(response); foreach (string cookie in response.Headers.GetAllAsString(HttpHeaderNames.SetCookie)) { Uri uu = new Uri(uri.Scheme + "://" + uri.Host + ":" + uri.Port + uri.Segments[0] + uri.Segments[1].TrimEnd('/')); log.Info("SetCookie received for uri " + uu + ": " + cookie); CookieHelper.saveCookies(uu, cookie); } } else if (msg is IHttpContent) { if (this.isNot(OCCUPIED)) { errorAsync(ch); return; } IHttpContent chunk = (IHttpContent)msg; IByteBuffer buf = chunk.Content; if (log.IsDebugEnabled) { if (buf.ReadableBytes > 0) { log.Debug("HTTP transport receiving [" + ch.Id + "]:\n" + buf.ToString(Encoding.UTF8)); } } message(buf); if (chunk is ILastHttpContent) { //http complete, go back to open so that it can be reused reuse(ctx); } } } }
/// <summary> /// Send a Head request to the specified Uri as an asynchronous operation. /// </summary> /// <param name="client">The <see cref="Windows.Web.Http.HttpClient"/> to send the request with.</param> /// <param name="requestUri">The <see cref="System.Uri"/> to send the request to.</param> /// <param name="content">The <see cref="Windows.Web.Http.IHttpContent"/> request content to send to the server.</param> /// <returns>A <see cref="System.Threading.Tasks.Task{T}"/> whose result is the <see cref="Windows.Web.Http.HttpResponseMessage"/> from the server.</returns> public async static Task <HttpResponseMessage> HeadAsync(this HttpClient client, Uri requestUri, IHttpContent content) { var method = new HttpMethod("HEAD"); var request = new HttpRequestMessage(method, requestUri) { Content = content }; return(await client.SendRequestAsync(request).AsTask().ConfigureAwait(false)); }
public Response(string url, IHttpContent cont, bool post) { this.url = url; this.cont = cont; this.post = post; }
/// <summary> /// Loads the data into a buffer with a maximum size of <see cref="int.MaxValue"/>. /// </summary> /// <param name="content">The content to load the data from</param> /// <returns>The task that loads the content</returns> public static Task LoadIntoBufferAsync(this IHttpContent content) { return(content.LoadIntoBufferAsync(int.MaxValue)); }
public HttpMessage(HttpHeaders headers, IHttpContent content) { Headers = headers; Content = content; }
protected void SetContentHeaders(IHttpContent content) { _request.Headers[HttpRequestHeader.ContentLength] = content.GetContentLength().ToString(); _request.ContentType = content.GetContentType(); }
private async Task<Response> getResponse(string url, IHttpContent cont, bool post) { Response res = new Response(); Uri uri = new Uri(url); var connectionP = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile(); if (connectionP == null) { res.hasInternet = false; Helper.message("I am sorry to tell you, but I cannot connect to the internet :(", "No Internet"); return res; } res.hasInternet = true; try { HttpResponseMessage response; if (post) { response = await client.PostAsync(uri, cont); } else { response = await client.GetAsync(uri); } response.EnsureSuccessStatusCode(); res.page = Regex.Replace(((await response.Content.ReadAsStringAsync()).Replace("\n", "").Replace("\\\"", "").Replace("\t", "")), " {2,}", ""); res.content = response; if (res.page.Contains("Forgot your password?")) { if (!await login()) { Frame rootFrame = Window.Current.Content as Frame; if (!rootFrame.Navigate(typeof(LandingPage), this)) { throw new Exception("Failed to create initial page"); } } if (post) { response = await client.PostAsync(uri, cont); } else { response = await client.GetAsync(uri); } } return res; } catch (Exception) { return res; } }
private async Task <HttpResponseMessage> MakeOneNoteRequest(string url, HttpMethod method, IHttpContent content = null, bool validatesPageId = true) { if (validatesPageId) { // Making the assumption that the ID this method got passed is the same as the one in the cache. // If this turns out to be an invalid assumption, we'll have to do some string parsing, or pass // in the ID separately or something. string oldId = CachedPageId; var validatedPageId = await ValidatePageId(CachedPageId); if (!validatedPageId.HasValue) { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } string newId = validatedPageId.ValueOrFailure(); if (newId != oldId) { // Hopefully we never have a scenario where the oldId isn't actually in the request URL... // If we DO, that's two reasons to parse out the ID url = url.Replace(oldId, newId); } } var message = new HttpRequestMessage(method, new Uri(url)); message.Content = content; var response = await _httpClient.SendRequestAsync(message); // For now, if we get an auth failure, only try to re-auth and make a new request once. // If this starts happening a lot, maybe we can add exponential back-off or something. if (response?.StatusCode == HttpStatusCode.Unauthorized) { await _msaAuthProvider.AuthenticateUserAsync(); response = await _httpClient.SendRequestAsync(message); return(response); } else { return(response); } }
//public virtual ViewResult View() //{ // return new ViewResult(); //} public virtual ContentResult ContentResult(IHttpContent content, HttpMediaTypeHeaderValue contentType) { return new ContentResult(content, contentType); }
/* * GetWeather initilizes a Result onject with all of the selected countries data. */ public async Task GetWeather(string cCode) { // Load local storage ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; // TempSetting represents the forma to convert kelvin to celsius. double tempSetting = 273.15; // Must confirm with local storage users selected temperature format. try { switch ((string)localSettings.Values["tempSetting"]) { case "Celsius": tempSetting = 273.15; break; case "Kelvin": tempSetting = -0; break; default: tempSetting = 273.15; break; } } catch { // If no local storage value is available do not show the prevSearch textbox. tempSetting = 1; } string cityCode = cCode; string apiKey = "&APPID=833dac87e9be3b3f86533d84b6064a84"; string url = "http://api.openweathermap.org/data/2.5/forecast?" + cityCode + apiKey; // Adapted from https://stackoverflow.com/questions/5566942/how-to-get-a-json-string-from-url var uri = new Uri(url); using (HttpResponseMessage response = await Client.GetAsync(uri)) { using (IHttpContent content = response.Content) { // Ensure that the httpRequest was a success. if (response.IsSuccessStatusCode) { this.httpSuccess = true; Debug.WriteLine("DEBUG : content =" + content); var json = await content.ReadAsStringAsync(); // Adapted from https://stackoverflow.com/questions/36516146/parsing-json-in-uwp Result = JsonConvert.DeserializeObject <RootObject>(json); SortedDays = new List <List <WeatherController> >(); // Create a list of weatherController objects to hold each hourly interval. List <WeatherController> sortedHours = new List <WeatherController>(); // A base time. DateTime prevDate = Convert.ToDateTime("2000-01-01"); int counter = 0; // iterate through Result list . for (int i = 0; i < Result.List.Count(); i++) { // if the date is greater than the previous date add the sortedHours to SortedDays. if (Convert.ToDateTime(Result.List[counter].Dt_txt).Date > prevDate.Date && counter != 0) { SortedDays.Add(sortedHours); sortedHours = new List <WeatherController>(); } WeatherController wController = new WeatherController { Dtime = Result.List[counter].Dt_txt, DayOfWeek = (Convert.ToDateTime(Result.List[counter].Dt_txt).DayOfWeek).ToString(), Temp = (Math.Truncate(Result.List[counter].Main.Temp - tempSetting) * 100) / 100, Humidity = Result.List[counter].Main.Humidity, Desc = Result.List[counter].Weather[0].Description, WindSpeed = Result.List[counter].Wind.Speed, Icon = "http://openweathermap.org/img/w/" + Result.List[counter].Weather[0].Icon + ".png", City = Result.City.Name, CoLong = Result.City.Coord.Lon, CoLat = Result.City.Coord.Lat }; sortedHours.Add(wController); prevDate = Convert.ToDateTime(Result.List[counter].Dt_txt); counter++; } // Add any left over sortedHours to SortedDays. if (sortedHours != null) { SortedDays.Add(sortedHours); } } else { this.httpSuccess = false; Debug.WriteLine("DEBUG: response error" + response.ReasonPhrase); } } }//using (HttpResponseMessage response = await Client.GetAsync(uri)) }
private async Task HandleQueueMessage(HttpResponseHeaderCollection headers, IHttpContent content) { string brokerPropertiesSource; if (!headers.TryGetValue("BrokerProperties", out brokerPropertiesSource)) { Log.Warning("Received Azure queue message without broker properties."); return; } var bodySource = await content.ReadAsStringAsync(); if (string.IsNullOrEmpty(bodySource)) { Log.Warning("Received Azure queue message with empty body."); return; } var brokerProperties = JObject.Parse(brokerPropertiesSource); var body = JObject.Parse(bodySource); Log.Verbose("Received valid Azure queue message."); MessageReceived?.Invoke(this, new MessageReceivedEventArgs(brokerProperties, body)); }
public HttpResponse(int status, IHttpContent content) { _status = status; _content = content; }
/// <summary> /// Eine POST-Anforderung mit einem Abbruchtoken als asynchronen Vorgang senden. /// </summary> /// <returns> /// Gibt <see cref="T:System.Threading.Tasks.Task`1"/> zurück. Das Aufgabenobjekt, das den asynchronen Vorgang darstellt. /// </returns> /// <param name="requestUri">Der URI, an den die Anforderung gesendet wird.</param><param name="content">Der Inhalt der HTTP-Anforderung, die an den Server gesendet wird.</param><param name="cancellationToken">Ein Abbruchtoken, das von anderen Objekten oder Threads verwendet werden kann, um Nachricht vom Abbruch zu empfangen.</param><exception cref="T:System.ArgumentNullException"><paramref name="requestUri"/> war null.</exception> public Task <HttpResponseMessage> PostAsync(string requestUri, IHttpContent content, CancellationToken cancellationToken) { return(m_orgHttpClient.PostAsync(requestUri, ((IProvideOrgHttpContent)content).OrgContent, cancellationToken)); }
/// <summary> /// Initializes a new instance of the <see cref="DevicePortalException"/> class. /// </summary> /// <param name="responseMessage">Http response message.</param> /// <param name="message">Optional exception message.</param> /// <param name="innerException">Optional inner exception.</param> public static async Task <DevicePortalException> CreateAsync( HttpResponseMessage responseMessage, string message = "", Exception innerException = null) { DevicePortalException error = new DevicePortalException(responseMessage.StatusCode, responseMessage.ReasonPhrase, responseMessage.RequestMessage != null ? responseMessage.RequestMessage.RequestUri : null, message, innerException); try { if (responseMessage.Content != null) { Stream dataStream = null; #if !WINDOWS_UWP using (HttpContent content = responseMessage.Content) { dataStream = new MemoryStream(); await content.CopyToAsync(dataStream).ConfigureAwait(false); // Ensure we point the stream at the origin. dataStream.Position = 0; } #else // WINDOWS_UWP IBuffer dataBuffer = null; using (IHttpContent messageContent = responseMessage.Content) { dataBuffer = await messageContent.ReadAsBufferAsync(); if (dataBuffer != null) { dataStream = dataBuffer.AsStream(); } } #endif // WINDOWS_UWP if (dataStream != null) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HttpErrorResponse)); HttpErrorResponse errorResponse = (HttpErrorResponse)serializer.ReadObject(dataStream); error.HResult = errorResponse.ErrorCode; error.Reason = errorResponse.ErrorMessage; // If we didn't get the Hresult and reason from these properties, try the other ones. if (error.HResult == 0) { error.HResult = errorResponse.Code; } if (string.IsNullOrEmpty(error.Reason)) { error.Reason = errorResponse.Reason; } dataStream.Dispose(); } } } catch (Exception) { // Do nothing if we fail to get additional error details from the response body. } return(error); }
public HttpResponse(HttpStatusCode status, IHttpContent content) : this((int)status, content) { }
internal static async Task <T> ReadAsJsonAsync <T>(this IHttpContent content) { string json = await content.ReadAsStringAsync(); return(JsonConvertHelper.JsonDeserialize <T>(json)); }
public XPRequestParam SetBody(IHttpContent body) { Body = body; return this; }
/// <summary> /// API for getting installation status. /// </summary> /// <returns>The status</returns> #pragma warning disable 1998 public async Task <ApplicationInstallStatus> GetInstallStatus() { ApplicationInstallStatus status = ApplicationInstallStatus.None; Uri uri = Utilities.BuildEndpoint( this.deviceConnection.Connection, InstallStateApi); HttpBaseProtocolFilter httpFilter = new HttpBaseProtocolFilter(); httpFilter.AllowUI = false; if (this.deviceConnection.Credentials != null) { httpFilter.ServerCredential = new PasswordCredential(); httpFilter.ServerCredential.UserName = this.deviceConnection.Credentials.UserName; httpFilter.ServerCredential.Password = this.deviceConnection.Credentials.Password; } using (HttpClient client = new HttpClient(httpFilter)) { this.ApplyHttpHeaders(client, HttpMethods.Get); IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.GetAsync(uri); while (responseOperation.Status != AsyncStatus.Completed) { } using (HttpResponseMessage response = responseOperation.GetResults()) { if (response.IsSuccessStatusCode) { if (response.StatusCode == HttpStatusCode.Ok) { // Status code: 200 if (response.Content != null) { Stream dataStream = null; IBuffer dataBuffer = null; using (IHttpContent messageContent = response.Content) { IAsyncOperationWithProgress <IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync(); while (bufferOperation.Status != AsyncStatus.Completed) { } dataBuffer = bufferOperation.GetResults(); if (dataBuffer != null) { dataStream = dataBuffer.AsStream(); } } if (dataStream != null) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(HttpErrorResponse)); HttpErrorResponse errorResponse = (HttpErrorResponse)serializer.ReadObject(dataStream); if (errorResponse.Success) { status = ApplicationInstallStatus.Completed; } else { throw new DevicePortalException(response.StatusCode, errorResponse, uri); } } else { throw new DevicePortalException(HttpStatusCode.Conflict, "Failed to deserialize GetInstallStatus response."); } } } else if (response.StatusCode == HttpStatusCode.NoContent) { // Status code: 204 status = ApplicationInstallStatus.InProgress; } } else { throw new DevicePortalException(response); } } } return(status); }
/// <summary> /// Gets the root certificate from the device. /// </summary> /// <param name="acceptUntrustedCerts">Whether or not we should accept untrusted certificates.</param> /// <returns>The device certificate.</returns> #pragma warning disable 1998 public async Task <Certificate> GetRootDeviceCertificate(bool acceptUntrustedCerts = false) { Certificate certificate = null; bool useHttps = true; // try https then http while (true) { Uri uri = null; if (useHttps) { uri = Utilities.BuildEndpoint(this.deviceConnection.Connection, RootCertificateEndpoint); } else { Uri baseUri = new Uri(string.Format("http://{0}", this.deviceConnection.Connection.Authority)); uri = Utilities.BuildEndpoint(baseUri, RootCertificateEndpoint); } try { HttpBaseProtocolFilter requestSettings = new HttpBaseProtocolFilter(); requestSettings.AllowUI = false; if (acceptUntrustedCerts) { requestSettings.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); } using (HttpClient client = new HttpClient(requestSettings)) { this.ApplyHttpHeaders(client, HttpMethods.Get); IAsyncOperationWithProgress <HttpResponseMessage, HttpProgress> responseOperation = client.GetAsync(uri); TaskAwaiter <HttpResponseMessage> responseAwaiter = responseOperation.GetAwaiter(); while (!responseAwaiter.IsCompleted) { } using (HttpResponseMessage response = responseOperation.GetResults()) { this.RetrieveCsrfToken(response); using (IHttpContent messageContent = response.Content) { IAsyncOperationWithProgress <IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync(); TaskAwaiter <IBuffer> readBufferAwaiter = bufferOperation.GetAwaiter(); while (!readBufferAwaiter.IsCompleted) { } certificate = new Certificate(bufferOperation.GetResults()); if (!certificate.Issuer.Contains(DevicePortalCertificateIssuer)) { certificate = null; throw new DevicePortalException( (HttpStatusCode)0, "Invalid certificate issuer", uri, "Failed to get the device certificate"); } } } } return(certificate); } catch (Exception e) { if (useHttps) { useHttps = false; } else { throw e; } } } }
public HttpResponse(int statusCode, string responseMessage, HttpHeaders headers, IHttpContent content) : base(headers, content) { StatusCode = statusCode; ResponseMessage = responseMessage; }
public async Task<bool> getResponse(string url, IHttpContent cont, bool post) { try { Uri uri = new Uri(url); HttpClient client = new HttpClient(); HttpResponseMessage response; if (post) { response = await client.PostAsync(uri, cont); } else { response = await client.GetAsync(uri); } if (!response.IsSuccessStatusCode) { return true; } page = Regex.Replace(((await response.Content.ReadAsStringAsync()).Replace("\n", "").Replace("\\\"", "").Replace("\t", "")), " {2,}", ""); pageCouldNotBeFound = false; try { htmldoc = new HtmlDocument(); htmldoc.LoadHtml(page); firstNode = htmldoc.DocumentNode; } catch(Exception) {} content = response; return false; } catch (Exception) { return true; } }
public HttpResponse OK(IHttpContent content) { return new HttpResponse(HttpStatusCode.OK, content); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultHttpRequestMessage"/> class. /// </summary> /// <param name="method">The request method</param> /// <param name="requestUri">The request URI</param> /// <param name="headers">The request headers to be used for the request</param> /// <param name="content">The content of the request body or NULL if no content</param> public DefaultHttpRequestMessage(Method method, [NotNull] Uri requestUri, [NotNull] IHttpHeaders headers, [CanBeNull] IHttpContent content) { Method = method; RequestUri = requestUri; Headers = headers; Version = new Version(1, 1); Content = content; }
/// <summary> /// Returns a range of elements from the source, if the elements are not local it will fetch them from the interwebs /// This can take multiple web calls to get the list, so this can be slow. If there aren't enough elements remaining /// we will return as many as we can get. /// THIS IS NOT THREAD SAFE /// </summary> /// <param name="bottom">The bottom range, inclusive</param> /// <param name="top">The top of the range, exclusive</param> /// <returns></returns> public async Task <List <Element <T> > > FetchElements(int bottom, int top) { if (top <= bottom) { throw new Exception("top can't be larger than bottom!"); } int sanityCheckCount = 0; while (true) { // See if we now have what they asked for, OR the list has elements but we don't have an after. // (this is the case when we have hit the end of the list) // #bug!?!? At some point I changed the children count in the after check to sanityCheckCount == 0, but I can't remember why // and it breaks lists that have ends. There is some bug where something doesn't try to refresh or something... if (m_currentElementList.Children.Count >= top || (m_currentElementList.Children.Count != 0 && m_currentElementList.After == null) || (sanityCheckCount > 25)) { // Return what they asked for capped at the list size int length = top - bottom; int listLength = m_currentElementList.Children.Count - bottom; length = Math.Min(length, listLength); // Set what the top was we returned. m_lastTopGet = bottom + length; return(m_currentElementList.Children.GetRange(bottom, length)); } // Figure out how many we need still. int numberNeeded = top - m_currentElementList.Children.Count; // Make the request. IHttpContent webResult = await MakeRequest(numberNeeded, m_currentElementList.After); // This will hold the root RootElement <T> root = null; // Get the input stream and json reader. // NOTE!! We are really careful not to use a string here so we don't have to allocate a huge string. IInputStream inputStream = await webResult.ReadAsInputStreamAsync(); using (StreamReader reader = new StreamReader(inputStream.AsStreamForRead())) using (JsonReader jsonReader = new JsonTextReader(reader)) { // Check if we have an array root or a object root if (m_isArrayRoot) { // Parse the Json as an object JsonSerializer serializer = new JsonSerializer(); List <RootElement <T> > arrayRoot = await Task.Run(() => serializer.Deserialize <List <RootElement <T> > >(jsonReader)); // Use which ever list element we want. if (m_takeFirstArrayRoot) { root = arrayRoot[0]; } else { root = arrayRoot[1]; } } else { // Parse the Json as an object JsonSerializer serializer = new JsonSerializer(); root = await Task.Run(() => serializer.Deserialize <RootElement <T> >(jsonReader)); } } // Copy the new contents into the current cache m_currentElementList.Children.AddRange(root.Data.Children); // Update the before and after m_currentElementList.After = root.Data.After; m_currentElementList.Before = root.Data.Before; sanityCheckCount++; } }