diff --git a/src/Agent/NewRelic/Agent/Core/Utilization/VendorHttpApiRequestor.cs b/src/Agent/NewRelic/Agent/Core/Utilization/VendorHttpApiRequestor.cs index 3a67f59eeb..d14f492a7c 100644 --- a/src/Agent/NewRelic/Agent/Core/Utilization/VendorHttpApiRequestor.cs +++ b/src/Agent/NewRelic/Agent/Core/Utilization/VendorHttpApiRequestor.cs @@ -3,9 +3,14 @@ using System; using System.Collections.Generic; +using NewRelic.Agent.Extensions.Logging; + +#if NETFRAMEWORK using System.IO; using System.Net; -using NewRelic.Agent.Extensions.Logging; +#else +using System.Net.Http; +#endif namespace NewRelic.Agent.Core.Utilization { @@ -15,6 +20,16 @@ public class VendorHttpApiRequestor public virtual string CallVendorApi(Uri uri, string method, string vendorName, IEnumerable headers = null) { +#if NETFRAMEWORK + return CallWithWebRequest(uri, method, vendorName, headers); +#else + return CallWithHttpClient(uri, method, vendorName, headers); +#endif + } + +#if NETFRAMEWORK + private string CallWithWebRequest(Uri uri, string method, string vendorName, IEnumerable headers = null) + { try { var request = WebRequest.Create(uri); @@ -66,5 +81,56 @@ public virtual string CallVendorApi(Uri uri, string method, string vendorName, I return null; } } +#else + private static readonly Lazy httpClient = new Lazy(() => + new HttpClient + { + Timeout = TimeSpan.FromMilliseconds(WebReqeustTimeout) + }); + + + private string CallWithHttpClient(Uri uri, string method, string vendorName, IEnumerable headers = null) + { + try + { + var request = new HttpRequestMessage + { + RequestUri = uri, + Method = new HttpMethod(method) + }; + + if (headers != null) + { + foreach (var header in headers) + { + var separatorIndex = header.IndexOf(": "); + if (separatorIndex > -1) + { + var headerName = header.Substring(0, separatorIndex).Trim(); + var headerValue = header.Substring(separatorIndex + 2).Trim(); // +2 to skip past ": " + request.Headers.TryAddWithoutValidation(headerName, headerValue); + } + } + } + + var response = httpClient.Value.SendAsync(request).GetAwaiter().GetResult(); + if (!response.IsSuccessStatusCode) + { + var statusCode = response.StatusCode; + var statusDescription = response.ReasonPhrase ?? string.Empty; + // intentionally not passing the exception parameter here + Log.Debug("CallVendorApi ({0}) failed with WebException with status: {1}; message: {2}", vendorName, statusCode, statusDescription); + } + + return response.Content.ReadAsStringAsync().GetAwaiter().GetResult(); + } + catch (Exception ex) + { + // intentionally not passing the exception parameter here + Log.Debug($"CallVendorApi ({{0}}) failed: {ex.Message}", vendorName); + return null; + } + } +#endif } }