0
点赞
收藏
分享

微信扫一扫

c# - - - 发送 HTTP json 请求

一世独秀 07-20 06:00 阅读 21

代码

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace HttpJsonRequestExample
{
    class Program
    {
        private static readonly HttpClient client = new HttpClient();

        static async Task Main()
        {
            try
            {
                // 设置基础URL和默认请求头
                client.BaseAddress = new Uri("https://api.example.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

                // 示例1: 发送GET请求并解析JSON响应
                Console.WriteLine("发送GET请求...");
                await GetDataAsync("api/data");

                // 示例2: 发送POST请求并带上JSON数据
                Console.WriteLine("\n发送POST请求...");
                await PostDataAsync("api/submit", new { Name = "John", Age = 30 });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
        }

        static async Task GetDataAsync(string requestUri)
        {
            HttpResponseMessage response = await client.GetAsync(requestUri);
            if (response.IsSuccessStatusCode)
            {
                string jsonString = await response.Content.ReadAsStringAsync();
                Console.WriteLine("响应数据:");
                Console.WriteLine(JsonSerializer.Serialize(
                    JsonDocument.Parse(jsonString), 
                    new JsonSerializerOptions { WriteIndented = true }));
            }
            else
            {
                Console.WriteLine($"请求失败,状态码: {response.StatusCode}");
            }
        }

        static async Task PostDataAsync(string requestUri, object data)
        {
            // 将对象序列化为JSON
            string jsonContent = JsonSerializer.Serialize(data);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            // 发送POST请求
            HttpResponseMessage response = await client.PostAsync(requestUri, content);
            if (response.IsSuccessStatusCode)
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine("服务器响应:");
                Console.WriteLine(responseContent);
            }
            else
            {
                Console.WriteLine($"请求失败,状态码: {response.StatusCode}");
            }
        }
    }
}    
举报

相关推荐

0 条评论