C#中请求HTTP接口api的方法

Posted 穆雄雄

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#中请求HTTP接口api的方法相关的知识,希望对你有一定的参考价值。

大家好,我是雄雄,欢迎关注微信公众号:雄雄的小课堂

前言

现在是:2023年2月15日22:14:30

搞代码的陈戌源都知道,哦,不好意思,是程序员,那个陈戌源好像是个“清官”…我们都知道,在java中调用api接口很简单,网上也有好多封装好的依赖,我们在项目中直接添加依赖,通过方法直接调用即可。
调用接口离不开传参,传参离不开json数据处理,java中也有线程的fastjson,想怎么用怎么用,但是在C#中调用接口确不大一样,今天我们就来看看在C#中如何调用api接口以及json数据的处理。

apipost中的接口

首先我们来看一下接口是啥样的。

该接口就是一个正常的post接口,请求的地址为:

http://127.0.0.1:8055/DaenWxHook/client/

请求时我们需要传入一个json数据的参数,如下:


    "type": "Q0000",
    "data": 
    

请求返回的json数据如下所示:


	"code": 200,
	"msg": "正常",
	"result": 
		"startTimeStamp": "16762e14307",
		"startTime": "2023年2月12日23时5分7秒",
		"runTime": "1天9时33分13秒",
		"recv": 1859,
		"send": 15,
		"wxNum": "muxiongxiosnssg701xxxx",
		"nick": "X[emoji=05F5]\\b",
		"wxid": "wxid_2sxs8edsw2glcgw522"
	,
	"wxid": "xxxxx",
	"port": 8055,
	"pid": 22820,
	"flag": "",
	"timestamp": "1676335100119"

C#中调用接口

  1. 新建一个工具类,这个工具类中就是专门负责请求接口的,包含postget方式,源代码如下:
using System;
using System.IO;
using System.Net;
using System.Text;

namespace Common

    public class Http
    
        #region IIS服务地址
        public String HostUrl = "http://127.0.0.1:8055";//本地测试
        //public String HostUrl = "http://192.168.10.109:64111";//真实环境
        #endregion

        #region HttpPost提交
        public string HttpPost(string apiUrl, string postDataStr)
        
            try
            
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HostUrl + "/" + apiUrl);
                request.Method = "POST";
                request.ContentType = "application/json";
                Stream requestStream = request.GetRequestStream();
                StreamWriter myStreamWriter = new StreamWriter(requestStream, Encoding.GetEncoding("utf-8"));
                myStreamWriter.Write(postDataStr);
                myStreamWriter.Flush();
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                
                    Stream myResponseStream = response.GetResponseStream();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                    string retString = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();
                    return retString;
                
                throw new Exception(response.StatusCode.ToString());
            
            catch (Exception e)
            
                Console.WriteLine("有异常了!");
                //Common.Logs.SaveLog("C:\\\\AlphaErrLog", "HTTP" + apiUrl, "HTTP[" + apiUrl + "]==Message:" + e.Message + "StackTrace:" + e.StackTrace);
                return "";
            
        
        #endregion

        #region HttpGet请求
        public string HttpGet(string Url)
        
            string retString = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "GET";
            try
            
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                //获取内容
                using (StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")))
                
                    myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponseStream.Close();
                
                return retString;
            
            catch (Exception)
            
                throw;
            
        
        #endregion

        #region HttpPostForXML
        public string HttpPostForXML(string url, string postData)
        
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/xml";
            req.Credentials = CredentialCache.DefaultCredentials; //防止出现403禁止访问
            byte[] data = Encoding.UTF8.GetBytes(postData);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            
                result = reader.ReadToEnd();
                return result;
            
        
        #endregion
    


  1. 创建son格式化工具类JsonHelper

将对象序列化为JSON格式

/// <summary>
        /// 将对象序列化为JSON格式
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>json字符串</returns>
        public static string SerializeObject(object o)
        
            var serializerSettings = new JsonSerializerSettings
            
                // 设置为驼峰命名
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            ;
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(o,Formatting.None,serializerSettings);
            return json;
        

解析JSON字符串生成对象实体

/// <summary>
        /// 解析JSON字符串生成对象实体
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="json">json字符串(eg."ID":"112","Name":"石子儿")</param>
        /// <returns>对象实体</returns>
        public static T DeserializeJsonToObject<T>(string json) where T : class
        
            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            StringReader sr = new StringReader(json);
            object o = serializer.Deserialize(new Newtonsoft.Json.JsonTextReader(sr), typeof(T));
            T t = o as T;
            return t;
        

解析JSON数组生成对象实体集合

 /// <summary>
        /// 解析JSON数组生成对象实体集合
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="json">json数组字符串(eg.["ID":"112","Name":"石子儿"])</param>
        /// <returns>对象实体集合</returns>
        public static List<T> DeserializeJsonToList<T>(string json) where T : class
        
            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            StringReader sr = new StringReader(json);
            object o = serializer.Deserialize(new Newtonsoft.Json.JsonTextReader(sr), typeof(List<T>));
            List<T> list = o as List<T>;
            return list;
        

反序列化JSON到给定的匿名对象

/// <summary>
        /// 反序列化JSON到给定的匿名对象.
        /// </summary>
        /// <typeparam name="T">匿名对象类型</typeparam>
        /// <param name="json">json字符串</param>
        /// <param name="anonymousTypeObject">匿名对象</param>
        /// <returns>匿名对象</returns>
        public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
        
            T t = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
            return t;
        

从本地文件加载,转为一个对象Model

/// <summary>
        /// 从本地文件加载,转为一个对象Model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        public static T FileLoad<T>(string path)
        
            try
            
                StreamReader file = File.OpenText(path);
                Newtonsoft.Json.JsonTextReader reader = new Newtonsoft.Json.JsonTextReader(file);
                Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                object o = serializer.Deserialize(reader, typeof(T));
                file.Close();
                return (T)o;
            
            catch (Exception)
            
                return default(T);
            
        

        public static T Copy<T>(T val)
        
            string s = JsonHelper.SerializeObject(val);
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(s);
        

        public static object DeserializeObject(string rawText, Type type)
        
            return Newtonsoft.Json.JsonConvert.DeserializeObject(rawText, type);
        

从本地文件加载,转为ModelList


/// <summary>
        /// 从本地文件加载,转为ModelList
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        public static List<T> FileLoadList<T>(string path) where T : class
        
            StreamReader file = File.OpenText(path);
            Newtonsoft.Json.JsonTextReader reader = new Newtonsoft.Json.JsonTextReader(file);
            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            object o = serializer.Deserialize(reader, typeof(List<T>));
            file.Close();
            List<T> list = o as List<T>;
            return list;
        

  1. 接下来我们看看如何调用,因为传参需要传递一个json格式的数据,所以我先用字典集合存放起来,然后格式化成json数据,传上去。

 private void Form1_Load(object sender, EventArgs e)
        
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("type", "Q0000");
            string param = JsonHelper.SerializeObject(dic);
            Console.WriteLine("参数是:"+ param);
            string result = http.HttpPost(path, param);
            Console.WriteLine("请求结果是:"+result);

        

data里面是空的也行,所以我就没有传。

以上是关于C#中请求HTTP接口api的方法的主要内容,如果未能解决你的问题,请参考以下文章

C#如何拿到从http上返回JSON数据?

C#从http上拿返回JSON数据

短信平台接口调用方法参考

转Java模拟http请求,调用外部api接口:HttpURLConnection和HttpClient的区别

C# WEB API 从 HTTP2 到 SPDY 的协议更改

HTTP API接口设计规范