2023-01-21 20:02:33 -08:00
|
|
|
using System;
|
2017-07-01 19:43:51 -07:00
|
|
|
using System.Diagnostics;
|
2016-08-30 20:31:14 -07:00
|
|
|
using System.IO;
|
2023-01-21 20:02:33 -08:00
|
|
|
using System.Net.Http;
|
2016-08-30 20:31:14 -07:00
|
|
|
|
2022-06-18 11:04:24 -07:00
|
|
|
namespace PKHeX.Core;
|
|
|
|
|
|
|
|
public static class NetUtil
|
2016-08-30 20:31:14 -07:00
|
|
|
{
|
2022-06-18 11:04:24 -07:00
|
|
|
public static string? GetStringFromURL(Uri url)
|
2016-08-30 20:31:14 -07:00
|
|
|
{
|
2022-06-18 11:04:24 -07:00
|
|
|
try
|
2016-08-30 20:31:14 -07:00
|
|
|
{
|
2022-06-18 11:04:24 -07:00
|
|
|
var stream = GetStreamFromURL(url);
|
|
|
|
if (stream == null)
|
2016-08-30 20:31:14 -07:00
|
|
|
return null;
|
2018-07-26 19:34:27 -07:00
|
|
|
|
2022-06-18 11:04:24 -07:00
|
|
|
using var reader = new StreamReader(stream);
|
|
|
|
return reader.ReadToEnd();
|
|
|
|
}
|
|
|
|
// No internet?
|
|
|
|
catch (Exception e)
|
2019-01-25 16:51:58 -08:00
|
|
|
{
|
2022-06-18 11:04:24 -07:00
|
|
|
Debug.WriteLine(e.Message);
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private static Stream? GetStreamFromURL(Uri url)
|
|
|
|
{
|
|
|
|
// The GitHub API will fail if no user agent is provided
|
2023-01-21 20:02:33 -08:00
|
|
|
using var client = new HttpClient();
|
|
|
|
const string agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36";
|
|
|
|
client.DefaultRequestHeaders.Add("User-Agent", agent);
|
|
|
|
var response = client.GetAsync(url).Result;
|
|
|
|
return response.IsSuccessStatusCode ? response.Content.ReadAsStreamAsync().Result : null;
|
2016-08-30 20:31:14 -07:00
|
|
|
}
|
|
|
|
}
|