C#发起Get、Post请求
2025年1月19日大约 1 分钟
C#发送 Get 请求,携带请求头,返回字符串数据
public static string Get(string url)
{
//var token = GetTokent();
using HttpClient client = new HttpClient();
// 设置请求头
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer xxxxx");
// 发送请求并获取响应
var getTask = client.GetAsync(url);
if (getTask.IsCanceled)
throw getTask.Exception;
if (getTask.IsFaulted)
throw getTask.Exception;
HttpResponseMessage getResponse = getTask.Result;
getResponse.EnsureSuccessStatusCode();
var result = getResponse.Content.ReadAsStringAsync().Result;
// 返回想要的结果
return result;
}
c#发起 Get 请求,返回二进制流,下载文件
public static void DownloadFile(string url, string savePath)
{
using var httpClient = new HttpClient();
httpClient.Timeout = TimeSpan.FromMinutes(2);
// 设置请求头
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer xxxxxx");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
// 发送Get请求
var getTask = httpClient.GetAsync(url);
if (getTask.IsCanceled)
throw getTask.Exception;
if (getTask.IsFaulted)
throw getTask.Exception;
HttpResponseMessage getResponse = getTask.Result;
getResponse.EnsureSuccessStatusCode();
// 接收二进制流,保存文件
using var fs = new FileStream(savePath, FileMode.Create);
var stram = getTask.Result.Content.ReadAsStreamAsync().Result;
stram.CopyTo(fs);
}
C#发送 Post 请求,携带请求头、请求体
public static string Post(string url)
{
using var client = new HttpClient();
// 添加请求头
//client.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8"); // 这种方式添加请求头会报错
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
// 添加请求体
var body = new Dictionary<string, string>()
{
{ "app_id","xxxxx"},
{ "app_secret","xxxx"},
};
// 请求体数据(JSON格式)
var content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
// 发送POST请求并获取响应
var postTask = client.PostAsync(url, content);
postTask.Wait();
if (postTask.IsCanceled)
{
throw postTask.Exception;
}
if (postTask.IsFaulted)
{
throw postTask.Exception;
}
HttpResponseMessage postResponse = postTask.Result;
HttpResponseMessage rest = postResponse.EnsureSuccessStatusCode();
if (rest.IsSuccessStatusCode)
{
// 读取响应内容
string responseBody = postResponse.Content.ReadAsStringAsync().Result;
// 返回想要的数据
return responseBody;
}
else
{
throw new Exception("Request failed with status code: " + postResponse.StatusCode);
}
}