Skip to content

Instantly share code, notes, and snippets.

@sinclairtarget
Created June 14, 2018 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sinclairtarget/5fc8c0d3a35a35d63f84d713634a1d97 to your computer and use it in GitHub Desktop.
Save sinclairtarget/5fc8c0d3a35a35d63f84d713634a1d97 to your computer and use it in GitHub Desktop.
HttpClient Test
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.InteropServices;
namespace dotnet_console
{
class Program
{
public static void Main(string[] args)
{
string version = typeof(RuntimeEnvironment).GetTypeInfo()
.Assembly
.GetCustomAttribute<AssemblyFileVersionAttribute>()
.Version;
Console.WriteLine("Assembly file version: " + version);
Console.WriteLine(".NET Core version: " + GetNetCoreVersion());
string content = Task.Run(() => FetchString("http://motherfuckingwebsite.com", "/")).Result;
Console.WriteLine("Content:");
Console.WriteLine(content);
}
public static async Task<string> FetchString(string baseUrl, string path)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseUrl);
Console.WriteLine("Starting request...");
HttpResponseMessage response = await client.GetAsync("/");
if (!response.IsSuccessStatusCode)
throw new Exception("Request failed with status: " + response.StatusCode);
Console.WriteLine("Response received.");
string body = await response.Content.ReadAsStringAsync();
return body;
}
public static string GetNetCoreVersion()
{
var assembly = typeof(System.Runtime.GCSettings).GetTypeInfo().Assembly;
var assemblyPath = assembly.CodeBase.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries);
int netCoreAppIndex = Array.IndexOf(assemblyPath, "Microsoft.NETCore.App");
if (netCoreAppIndex > 0 && netCoreAppIndex < assemblyPath.Length - 2)
return assemblyPath[netCoreAppIndex + 1];
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment