protected static void ReadHeaders(JObject jobj, JsonSerializer serializer, HttpHeaders headers, HttpContent content) { JToken headersToken; if (jobj.TryGetValue("headers", out headersToken)) { var headersJobj = headersToken as JObject; if (headersJobj == null) throw new JsonSerializationException("\"headers\" property must be a JSON object token."); foreach (var prop in headersJobj) { var key = prop.Key; if (IsIgnoredHeader(key)) continue; var jValues = prop.Value; List<string> values = new List<string>(); if (jValues.Type == JTokenType.Array) { foreach (var item in (JArray)jValues) { if (item.Type != JTokenType.String) throw new JsonSerializationException("Header value must be a string."); values.Add(item.Value<string>()); } } else { if (jValues.Type != JTokenType.String) throw new JsonSerializationException("Header value must be a string."); values.Add(jValues.Value<string>()); } if (contentHeaderKeys.Contains(key)) { if (content == null) throw new JsonSerializationException("There is no content, unable to add content header " + key); content.Headers.Add(key, values); } else headers.Add(key, values); } } }
public WebClientResponseMessage Send(WebClientRequestMessage request) { Func<string, Action<BrowserContext>, BrowserResponse> browserMethod; switch (request.Method.ToUpper()) { case "POST": browserMethod = browser.Post; break; case "PATCH": browserMethod = browser.Patch; break; case "GET": browserMethod = browser.Get; break; default: throw new NotImplementedException(); } var uri = new Uri(request.Uri); var creds = Credentials; var browserResponse = browserMethod(request.Uri, bc => { bc.HttpRequest(); if (creds != null) { bc.BasicAuth(creds.UserName, creds.Password); } ((IBrowserContextValues) bc).QueryString = uri.Query; foreach (var kvp in request.Headers) { foreach (var v in kvp.Value) bc.Header(kvp.Key, v); } if (request.Data != null) { bc.Body(new MemoryStream(request.Data)); } }); var responseHeaders = new HttpHeaders( browserResponse .Headers .Select(x => new KeyValuePair<string, IEnumerable<string>>(x.Key, x.Value.WrapAsEnumerable()))); if (browserResponse.Context.Response != null && (!string.IsNullOrEmpty(browserResponse.Context.Response.ContentType))) { responseHeaders.Add("Content-Type", browserResponse.Context.Response.ContentType); } return new WebClientResponseMessage(request.Uri, browserResponse.Body.ToArray(), (HttpStatusCode) browserResponse.StatusCode, responseHeaders, "1.1"); }