当前位置:   article > 正文

C# 如何调用webApi接口_c# 调用webapi接口

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;
        }
    }

}



  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91

2.接口的调用

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

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

public class UserInfo 
{
        public string username { get; set; }
        public string password { get; set; }
}
  • 1
  • 2
  • 3
  • 4
  • 5

发送请求
这里依赖于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());
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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

请求方式二

            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);
			
			
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/550454
推荐阅读
相关标签
  

闽ICP备14008679号