当前位置:首页 > 技能相关 > C#与C++ > 正文内容

C# 调用webApi接口的方法(类库HttpClient)

admin1年前 (2024-01-15)C#与C++4310 修订时间:2024-06-13 16:44:45

一、类库HttpClient,用于发送http请求

类似于axios,ajax等,无第三方依赖。

注意,这里的请求类型为application/json,你可以根据自己的需求的不同进行封装

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace UnifyPayPlatAPI.Controller
{
    public class HttpClient
    {
        /// <summary>
        /// 接口地址
        /// </summary>
        public string Url { get; set; }
        /// <summary>
        /// 内容,body,fields参数
        /// </summary>
        public string Data { get; set; }
        /// <summary>
        /// Cookie,保证登录后,所有访问持有一个Cookie;
        /// </summary>
        static CookieContainer Cookie = new CookieContainer();
        /// <summary>
        /// Seivice Method ,post,get,delete,put,等等,支持大小写
        /// </summary>
        public string Method { get; set; }
        /// <summary>
        /// 请求头
        /// </summary>
        public Dictionary<string, string> Headers { get; set; }
        /// <summary>
        /// 请求体类型 ,如application/json
        /// </summary>
        public string ContentType { get; set; }
        /// <summary>
        /// HTTP访问
        /// </summary>
        public string AsyncRequest()
        {
            HttpWebRequest httpRequest = HttpWebRequest.Create(Url) as HttpWebRequest;
            httpRequest.Method = Method;
            if (Headers != null && Headers.Count > 0)
            {
                for (int i = 0; i < Headers.Keys.Count; i++)
                {
                    string key = Headers.Keys.ElementAt(i);
                    httpRequest.Headers.Add(key, Headers[key]);
                }
            }
            httpRequest.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType;
            httpRequest.CookieContainer = Cookie;
            httpRequest.Timeout = 1000 * 60 * 10;//10min
            using (Stream reqStream = httpRequest.GetRequestStream())
            {
                var bytes = UnicodeEncoding.UTF8.GetBytes(Data);
                reqStream.Write(bytes, 0, bytes.Length);
                reqStream.Flush();
            }
            using (var repStream = httpRequest.GetResponse().GetResponseStream())
            {
                using (var reader = new StreamReader(repStream))
                {
                    return ValidateResult(reader.ReadToEnd());
                }
            }
        }
        private static string ValidateResult(string responseText)
        {
            if (responseText.StartsWith("response_error:"))
            {
                return responseText.TrimStart("response_error:".ToCharArray());
            }
            return responseText;
        }
    }
}

二、Json依赖

依赖于Newtonsoft.Json,需要去NuGet安装;

image.png

三、请求方式

3.1 方式一

//创建访问webapi必备对象
HttpClient httpClient = new HttpClient();
httpClient.Url = apiUrl611;
httpClient.Data = JsonInput;
httpClient.Method = "Post";
var JsonOut = httpClient.AsyncRequest();
var iResult = JObject.Parse(httpClient.AsyncRequest());

3.2 方式二

string data = "{ "username": "zhangsan","password": "123456"}";
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("zhangsan","testToken123456");

//向后端发送请求
HttpClient httpClient = new HttpClient();
httpClient.Url = "http://localhost:5555/login";
httpClient.Method = "post";
httpClient.Data = data;
httpClient.Headers = headers;
//httpClient.ContentType = "application/json"; //不设置默认为application/json

//返回结果
//处理方式一
var iResult = JObject.Parse(httpClient.AsyncRequest());		
int code = iResult ["code"].Value<int>();
string message = iResult ["message"].Value<string>;
JArray roles = iResult ["roles"] as JArray;
JArray roles = JArray.Parse(iResult ["roles"]);

//处理方式二
string iResult  = httpClient.AsyncRequest();
//反序列化,当然你要先定义一个数据模型,负责接收反序列化后的数据
//为数据模型的类型
T res = JsonConvert.DeserializeObject<T>(iResult);

拓展:

C# 调用webApi接口的方法(类库RestSharp)

 您阅读本篇文章共花了: 

免责声明
本站内容均为博客主本人日常使用记录的存档,如侵犯你的权益请联系:lifei@zaiheze.com 546262132@qq.com 沟通删除事宜。本站仅带访问端口形式使用,已杜绝搜索引擎爬取。

扫描二维码推送至手机访问。

版权声明:本文由LIFEI - blog发布,如需转载请注明出处。

本文链接:http://www.lifeiai.com/?id=388

分享给朋友:

相关文章

Web API的创建3年前 (2022-11-07)
C# 第一篇 踏上征程 3年前 (2022-11-14)
C# 第二篇 基础语法3年前 (2022-11-14)
C# 第三篇 流程控制3年前 (2022-11-15)

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。