Skip to content

Commit

Permalink
chore: For netstandard2.0, use HttpClient in VendorHttpApiRequestor. (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
jaffinito authored Jun 20, 2024
1 parent 329fd59 commit 8b24d04
Showing 1 changed file with 67 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -15,6 +20,16 @@ public class VendorHttpApiRequestor

public virtual string CallVendorApi(Uri uri, string method, string vendorName, IEnumerable<string> 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<string> headers = null)
{
try
{
var request = WebRequest.Create(uri);
Expand Down Expand Up @@ -66,5 +81,56 @@ public virtual string CallVendorApi(Uri uri, string method, string vendorName, I
return null;
}
}
#else
private static readonly Lazy<HttpClient> httpClient = new Lazy<HttpClient>(() =>
new HttpClient
{
Timeout = TimeSpan.FromMilliseconds(WebReqeustTimeout)
});


private string CallWithHttpClient(Uri uri, string method, string vendorName, IEnumerable<string> 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
}
}

0 comments on commit 8b24d04

Please sign in to comment.