internal ContentType ExtractContentTypeFromResponse(IHttpWebResponse response) { ContentType result; if (HttpConverter.TryParseContentType(response.ContentType, out result)) { return(result); } var headers = response.Headers; const ContentType fallback = ContentType.ApplicationJson; if (headers == null) { return(fallback); } var contentTypeHeader = headers[HttpResponseHeader.ContentType]; if (contentTypeHeader == null) { return(fallback); } var contentType = HttpConverter.ContentType(contentTypeHeader); return(contentType); }
public WebRequester WithPayload(object data, ContentType type) { _contentTypeProvider = () => type; _payloadModifilerAsync = async req => { if (data == null) { return; } var serializer = _config.Advanced.Serializers.FirstOrDefault(s => s.ContentType.Contains(_contentTypeProvider())); if (serializer == null) { throw new Exception(string.Format("No Serializer registered for {0}", type)); } var serializedPayload = serializer.Serialize(data); var payloadAsBytes = Encoding.UTF8.GetBytes(serializedPayload); req.ContentLength = payloadAsBytes.Length; req.ContentType = HttpConverter.ContentType(_contentTypeProvider()); using (var stream = await Task <Stream> .Factory.FromAsync(req.BeginGetRequestStream, req.EndGetRequestStream, req)) { await stream.WriteAsync(payloadAsBytes, 0, payloadAsBytes.Length); } }; return(this); }
public void CanConvertNonSuccessCefsharpResponse() { //given an http response using (var response = new HttpResponseMessage(HttpStatusCode.RedirectMethod) { Content = new StringContent("I am some other content", Encoding.ASCII, "application/json"), ReasonPhrase = "Go elsewhere!" }) { response.Headers.Add("steve", "headerValue"); //when we convert it var converted = new HttpConverter().ToCefSharpResponse(response); //then the fields are all transferred correctly Assert.AreEqual(303, converted.StatusCode); CollectionAssert.AreEquivalent(new[] { new KeyValuePair <string, string>("steve", "headerValue"), new KeyValuePair <string, string>("Content-Type", "application/json; charset=us-ascii"), }, converted.Headers.ToDictionary()); Assert.AreEqual("application/json", converted.Mime); Assert.AreEqual("I am some other content", StreamToString(converted.Content, Encoding.ASCII)); Assert.AreEqual("Go elsewhere!", converted.ReasonPhrase); } }
public void CanConvertToCefsharpResponse() { //given an http response using (var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("I am some content", Encoding.UTF32, "random/encoding"), ReasonPhrase = "Yay!" }) { response.Headers.Add("steve", "headerValue"); //when we convert it var converted = new HttpConverter().ToCefSharpResponse(response); //then the fields are all transferred correctly Assert.AreEqual(200, converted.StatusCode); CollectionAssert.AreEquivalent(new[] { new KeyValuePair <string, string>("steve", "headerValue"), new KeyValuePair <string, string>("Content-Type", "random/encoding; charset=utf-32"), }, converted.Headers.ToDictionary()); Assert.AreEqual("random/encoding", converted.Mime); Assert.AreEqual("I am some content", StreamToString(converted.Content, Encoding.UTF32)); Assert.AreEqual("Yay!", converted.ReasonPhrase); } }
public void ShouldThrowExceptionIfStringDoesNotMatchContentType() { /* Setup */ const string nonMatch = "This is not a content type"; /* Test & Assert */ Assert.Throws <ArgumentException>(() => HttpConverter.ContentType(nonMatch)); }
public void ShouldThrowExceptionIfContentTypeIsUnknown() { /* Setup */ var type = ContentType.Unknown; /* Test & Assert */ Assert.Throws <ArgumentException>(() => HttpConverter.ContentType(type)); }
public void ShouldConvertMethodStringToEnum(string method, HttpMethod expectedResult) { /* Setup */ /* Test */ var result = HttpConverter.HttpMethod(method); /* Assert */ Assert.That(result, Is.EqualTo(expectedResult)); }
public void ShouldConvertContentTypeStringToEnum(string type, ContentType expectedResult) { /* Setup */ /* Test */ var result = HttpConverter.ContentType(type); /* Assert */ Assert.That(result, Is.EqualTo(expectedResult)); }
public void ShouldRetrunFalseIfStringCantBeParsedAsContentType(string contentTypeString) { /* Setup */ ContentType contentType; /* Test */ var result = HttpConverter.TryParseContentType(contentTypeString, out contentType); /* Assert */ Assert.That(result, Is.False); }
public void CanConvertFromCefSharpRequest() { var request = Substitute.For <IRequest>(); request.Method.Returns("POST"); request.Body.Returns("I am some content"); var headers = new NameValueCollection(); headers["Content-Type"] = "application/json; charset=us-ascii"; headers["Accept"] = "text/html"; request.Headers.Returns(headers); var converted = new HttpConverter().ToOwinHttpRequest(request); Assert.AreEqual("I am some content", converted.Content.ReadAsStringAsync().Result); Assert.AreEqual(HttpMethod.Post, converted.Method); Assert.AreEqual("text/html", converted.Headers.Accept.Single().MediaType); Assert.AreEqual("application/json", converted.Content.Headers.ContentType.MediaType); }
public async static Task <string> Request(string baseUri, string requestUri, string method = "Get", Dictionary <string, string> headers = null, string data = "", string contentType = "application/json") { var client = new HttpClient { BaseAddress = new Uri(baseUri) }; var request = new HttpRequestMessage(new HttpMethod(method), requestUri); if (headers != null) { foreach (var header in headers) { request.Headers.Add(header.Key, HttpConverter.Encode(header.Value, Encoding.UTF8)); } } if (!string.IsNullOrEmpty(data)) { request.Content = new StringContent(data); request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); } string content = null; try { var response = await client.SendAsync(request); content = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { throw new MessageCodeException(content, (int)response.StatusCode); } } catch (HttpRequestException ex) { throw new MessageCodeException(ex.Message); } return(content); }
public async Task <ResponseMessage> SendAsync( RequestMessage message, CancellationToken cancellationToken) { var taskCompletionSource = new TaskCompletionSource <ResponseMessage>(); cancellationToken.Register(() => taskCompletionSource.SetCanceled()); var httpRequestMessage = await HttpConverter.ToRequestAsync(message, cancellationToken); httpRequestMessage.Headers.Add(ProtocolConstants.REDProtocolVersionHeaderName, REDProtocolVersion); var task = HttpClient.SendAsync(httpRequestMessage, cancellationToken) .ContinueWith(async response => { if (response.IsFaulted) { taskCompletionSource.SetException(response.Exception); return; } if (response.IsCanceled) { taskCompletionSource.SetCanceled(); return; } if (!response.Result.Headers.TryGetValues(ProtocolConstants.REDResponseActionHeaderName, out var responseActions)) { responseActions = new[] { ResponseActions.Normal }; } switch (responseActions.Single()) { case ResponseActions.Yield: { var correlationId = response.Result.Headers .GetValues(ProtocolConstants.REDCorrelationIdHeaderName) .SingleOrDefault(); if (string.IsNullOrWhiteSpace(correlationId)) { throw new ProtocolException(ProtocolException.YieldCorrelationIdIsMissing); } TimeSpan?timeout = null; if (response.Result.Headers.TryGetValues(ProtocolConstants.REDYieldTimeoutHeaderName, out var yieldTimeoutStrings)) { var timeoutStr = yieldTimeoutStrings.SingleOrDefault(); timeout = TimeSpan.Parse(timeoutStr); } var trackedTask = new TaskInfo <ResponseMessage>(taskCompletionSource, timeout); if (!cancellationToken.IsCancellationRequested) { InMemoryTaskTracker.Track(correlationId, trackedTask); } break; } //case ResponseActions.Normal: default: { taskCompletionSource.SetResult( await HttpConverter.FromResponseAsync(response.Result, cancellationToken) ); break; } } }, cancellationToken).ConfigureAwait(false); return(await taskCompletionSource.Task); }