NewGaoKaoApi/New_College.Common/Helper/HtmlHeplerFetcher.cs

45 lines
1.6 KiB
C#

using Microsoft.DotNet.PlatformAbstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace New_College.Common
{
public static class HtmlHeplerFetcher
{
public static async Task<string> GetHtmlContentAsync(string url)
{
using (HttpClient client = new HttpClient())
{
try
{
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36");
client.DefaultRequestHeaders.Add("Sec-Ch-Ua","'Google Chrome';v='119','Chromium';v='119','Not?A_Brand';v='24'");
client.DefaultRequestHeaders.Add("Sec-Ch-Ua-Mobile", "?0");
client.DefaultRequestHeaders.Add("Sec-Ch-Ua-Platform", "Windows");
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
throw new HttpRequestException($"Failed to retrieve HTML. Status code: {response.StatusCode}");
}
}
catch (Exception ex)
{
throw new HttpRequestException($"Failed to retrieve HTML. {ex.Message}");
}
}
}
}
}