C#学习——Get、Post请求

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();

    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值