C# 如何调用webApi接口

1.封装HttpClient.cs

优先封装HttpClient.cs,用于发送http请求,类似于axios,ajax等等
自己创建一个HttpClient.cs,将以下代码拷贝进去即可,无需依赖
注意,这里的请求类型为application/json,你可以根据自己的需求的不同进行封装

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

namespace CustomReportForm
{
    
    


    public class HttpClient
    {
    
    
        /// <summary>
        /// Seivice URL
        /// </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;
        }
    }

}



2.接口的调用

将一个json的字符串数据发送到接口中,发送post请求

这里需要先定义一个数据模型

public class UserInfo 
{
    
    
        public string username {
    
     get; set; }
        public string password {
    
     get; set; }
}

发送请求
这里依赖于Newtonsoft.Json,需要去安装
右键项目-》管理NuGet程序包
在这里插入图片描述
在这里插入图片描述
安装成功,就看到就看看自己引用中是否存在Newtonsoft.Json,没有就手动添加到引用中吧

请求方式一

//向后端发送请求
HttpClient httpClient = new HttpClient();
httpClient.Url = "http://localhost:9523/login";
httpClient.Method = "post";

UserInfo userInfo = new UserInfo();
userInfo.username = "zhangsan";
userInfo.password = "1234756";

httpClient.Data = JsonConvert.SerializeObject(userInfo);
var iResult = JObject.Parse(httpClient.AsyncRequest());

发送请求成功
在这里插入图片描述

请求方式二

            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为数据模型的类型
			T res = JsonConvert.DeserializeObject<T>(iResult);
			
			

猜你喜欢

转载自blog.csdn.net/adsd1233123/article/details/127763360