private static RawResponse InitRawResponse(HttpResponseMessage response) { var raw = new RawResponse(); if (response != null) { raw.StatusCode = response.StatusCode; raw.StatusMessage = response.ReasonPhrase; response.Content.Headers.TryGetValues("Content-Type", out var values); raw.ContentType = string.Join("; ", values ?? new [] { "text/plain" }); } else { raw.StatusCode = HttpStatusCode.BadRequest; raw.ContentType = "text/plain"; raw.Body = new SdkError("Response is null. That's all I know."); } return(raw); }
public async Task <IRawResponse> RawRequest( HttpMethod method, string path, Values queryParams = null, object body = null, Authenticator authenticator = null, ITransportSettings options = null ) { var url = MakeUrl(path, queryParams, authenticator); var request = new HttpRequestMessage(method, url); request.Headers.Add(Constants.LookerAppiId, _settings.AgentTag); if (body != null) { if (body is string) { request.Content = new StringContent( body.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded"); } else { request.Content = new StringContent( JsonSerializer.Serialize(body, new JsonSerializerOptions { IgnoreNullValues = true }), Encoding.UTF8, "application/json"); } } if (authenticator != null) { request = await authenticator(request); } RawResponse result = new RawResponse(); HttpResponseMessage response = null; try { response = await _client.SendAsync(request); result = InitRawResponse(response); // if (response.IsSuccessStatusCode) await using var stream = await response.Content.ReadAsStreamAsync(); // Simple content conversion here to make body easily readable in consumers switch (SdkUtils.ResponseMode(result.ContentType)) { case ResponseMode.Binary: result.Body = SdkUtils.StreamToByteArray(stream); break; case ResponseMode.String: using (var sr = new StreamReader(stream)) { result.Body = await sr.ReadToEndAsync(); } break; case ResponseMode.Unknown: result.Body = SdkUtils.StreamToByteArray(stream); break; default: throw new ArgumentOutOfRangeException($"Unrecognized Content Type {result.ContentType}"); } } catch (Exception e) { result = InitRawResponse(response); result.Body = e; } return(result); }