c#——请求一个URL接口

本文介绍了如何在.NET4.6环境下利用async和HttpClient进行异步网络请求,以及如何处理POST和GET请求,并使用Newtonsoft.Json库解析返回的JSON数据。
摘要由CSDN通过智能技术生成

.net 4.6环境下

.net4.6支持异步编程

命名空间:

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

创建一个异步方法发送请求:

public static async Task<string> CallWebAPIAsync(string url, string method, string data)
{
    using (var client = new HttpClient())
    {
        HttpResponseMessage response;
        if (method.ToUpper() == "GET")
        {
            // 如果是GET请求
            response = await client.GetAsync(url);
        }
        else if (method.ToUpper() == "POST")
        {
            // 如果是POST请求
            var content = new StringContent(data, Encoding.UTF8, "application/json");
            response = await client.PostAsync(url, content);
        }
        else
        {
            throw new InvalidOperationException("Unsupported method: " + method);
        }

        // 确保HTTP请求成功
        response.EnsureSuccessStatusCode();

        // 读取并返回响应内容
        return await response.Content.ReadAsStringAsync();
    }
}

调用这个方法:

private async void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string data = "{\"id\":\"\",\"properties\":\"\"}";
                string url = "";
                string method="POST";//GET
                string result = await callWebApiAsync(url,method, data);
                richTextBox1.Text = result;
            }
            catch (Exception ex)
            {
                Console.WriteLine("发生错误: " + ex.Message);
            }
        }

一定要保证,调用时调用的方法满足异步操作。方法应该标记为async 并返回Task。

如果还有其他需求,比如返回的是一个标准的json格式字符串,那我们可以进行加工,转化为我们需要的json格式数据。

这里需要添加引用“Newtonsoft.Json”

首先找到返回的字符串的json格式,我们一般使用json.cn进行转化,选择“json转c#实体

将返回结果复制进去即可得到json格式,将格式复制在代码中,例如

public class ResultItem
    {
        /// <summary>
        /// 姓名
        /// </summary>
        public string name{ get; set; }
        
    }

    public class Root
    {
        /// <summary>
        /// 
        /// </summary>
        public List<ResultItem> result { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string success { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string errorMsg { get; set; }
    }

然后进行转化:

try
            {
                string data = "{\"id\":\"\",\"properties\":{ \name\": \"\"}}";
                string url = "";
                string method="POST";//GET
                string result = await callWebApiAsync(url,method, data);
                var v = JsonConvert.DeserializeObject<Root>(result);
                v.result.ForEach(x => {
                    if (x.name.StartsWith("name******")) {
                        richTextBox1.Text += x.name+"\n";
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("发生错误: " + ex.Message);
            }

.net 4.0环境下

.net4.0没有原生的async、 await

.net不支持HttpClient

通常会使用webclient、httpwebrequest来进行HTTP请求。

命名空间:

using Newtonsoft.Json;
using System.Net;
using System.IO;

http请求:

private static string PostHTTP(string url, string data)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json";
            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(data);
            }

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    return reader.ReadToEnd();
                }
            }
        }

调用方法:

private void get()
        {
            try
            {
                string url = "";
                string data = "{\"id\":\"\",\"properties\":{ \"name\": \"\"}}";
                string result = PostHTTP(url, data);
                var v = JsonConvert.DeserializeObject<Root>(result);
                v.result.ForEach(x => {
                    if (x.bl_item_item_id.StartsWith("5001*****"))
                    {
                        richTextBox1.Text += x.name + "\n";
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }




    public class ResultItem
    {
        /// <summary>
        /// 姓名
        /// </summary>
        public string name { get; set; }
        
    }

    public class Root
    {
        /// <summary>
        /// 
        /// </summary>
        public List<ResultItem> result { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string success { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public string errorMsg { get; set; }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值