get 请求
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
// 设置GET请求的URL
string url = "http://101.37.77.138:3003/test";
try
{
// 发送GET请求
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine("Failed to make request. Status code: " + response.StatusCode);
}
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
Console.ReadKey();
}
}
Post请求
需要安装 Newtonsoft.Json 包
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text;
class Program
{
static async Task Main(string[] args)
{
using (var client = new HttpClient())
{
// 要发送的数据
var postData = new
{
key1 = "value1",
key2 = "value2"
// 可以根据需要添加更多参数
};
// 设置请求URL
string url = "http://101.37.77.138:3003/testPost";
// 设置请求头 (写了反而报错?)
//client.DefaultRequestHeaders.Add("Content-Type", "application/json");
// 将对象转换为JSON字符串
string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(postData);
// 创建请求内容
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
// 创建请求
HttpResponseMessage response = await client.PostAsync(url, content);
// 检查响应状态码
if (response.IsSuccessStatusCode)
{
// 读取响应内容
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine("Response Content: " + result);
}
else
{
Console.WriteLine("Request failed: " + response.StatusCode);
}
}
Console.ReadKey();
}
}