主要更新了http相关的内容
This commit is contained in:
77
Ramitta/HttpHelper.cs
Normal file
77
Ramitta/HttpHelper.cs
Normal file
@@ -0,0 +1,77 @@
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
|
||||
namespace Ramitta.lib
|
||||
{
|
||||
public static class HttpHelper
|
||||
{
|
||||
// 异步发送HTTP GET请求
|
||||
public static async Task<string> SendHttpGetAsync(string url, int timeout = 10000)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||||
request.Method = "GET";
|
||||
request.Timeout = timeout;
|
||||
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36";
|
||||
|
||||
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
|
||||
using (Stream stream = response.GetResponseStream())
|
||||
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
|
||||
{
|
||||
return await reader.ReadToEndAsync();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception($"GET请求失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<string> SendHttpPostAsync(string url, string jsonData, int timeout = 10000)
|
||||
{
|
||||
try
|
||||
{
|
||||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||||
request.Method = "POST";
|
||||
request.Timeout = timeout;
|
||||
request.ContentType = "application/json";
|
||||
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
|
||||
|
||||
byte[] data = Encoding.UTF8.GetBytes(jsonData);
|
||||
request.ContentLength = data.Length;
|
||||
|
||||
using (Stream requestStream = await request.GetRequestStreamAsync())
|
||||
{
|
||||
await requestStream.WriteAsync(data, 0, data.Length);
|
||||
}
|
||||
|
||||
using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
|
||||
using (Stream responseStream = response.GetResponseStream())
|
||||
using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
|
||||
{
|
||||
return await reader.ReadToEndAsync();
|
||||
}
|
||||
}
|
||||
catch (WebException ex)
|
||||
{
|
||||
WebResponse errorResponse = ex.Response;
|
||||
if (errorResponse is HttpWebResponse httpErrorResponse)
|
||||
{
|
||||
using (Stream errorStream = httpErrorResponse.GetResponseStream())
|
||||
using (StreamReader errorReader = new StreamReader(errorStream, Encoding.UTF8))
|
||||
{
|
||||
string errorContent = await errorReader.ReadToEndAsync();
|
||||
throw new Exception($"HTTP错误 {(int)httpErrorResponse.StatusCode} ({httpErrorResponse.StatusCode}): {errorContent}");
|
||||
}
|
||||
}
|
||||
throw new Exception("网络错误: " + ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception("POST请求失败: " + ex.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user