zoukankan      html  css  js  c++  java
  • .net core HttpClient

    最近在写项目,这里打算整理出项目中比较常用的功能。

    通常我们发送http请求是在前端使用表单或者ajax,那么.net core后台发送http请求该如何呢?

    这里我使用HttpClient

    因为通常提交的方法是post或者get,我使用简单工厂模式来设计此功能。

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace Tools.HttpClientHelper
    {
        public abstract class AbsHttpHelper
        {
            //请求的主机
            public string baseAddr = string.Empty;
            //是否启用验证
            public bool isAuth = false;
            //验证字符串
            public string auth = string.Empty;//"Bearer "+token
            //请求路径
            public string path = string.Empty;
    
            public abstract string GetResult();
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Text;
    
    namespace Tools.HttpClientHelper
    {
        public class GetHelper: AbsHttpHelper
        {
    
            /// <summary>
            /// 
            /// </summary>
            /// <param name="baseAddr">访问的主机</param>
            /// <param name="auth">验证字符串</param>
            /// <param name="path">请求的路径</param>
            public GetHelper(string baseAddr, string auth, string path)
            {
                this.baseAddr = baseAddr;
                this.auth = auth;
                this.path = path;
            }
    
            public override string GetResult()
            {
                string resultContent = string.Empty;
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseAddr);
                    var t = client.GetAsync(path);
                    t.Wait();
                    var result = t.Result;
                    resultContent = result.Content.ReadAsStringAsync().Result;
                }
                return resultContent;
            }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Text;
    
    namespace Tools.HttpClientHelper
    {
        public class PostHelper:AbsHttpHelper
        {
            //发送的数据
            private FormUrlEncodedContent content = null;
    
            /// <summary>
            /// 构造方法
            /// </summary>
            /// <param name="baseAddr">请求的主机</param>
            /// <param name="auth">验证字符串</param>
            /// <param name="path">请求路径</param>
            /// <param name="isAuth">是否启用验证</param>
            /// <param name="content">发送的数据</param>
            public PostHelper(string baseAddr, string auth, string path, bool isAuth, FormUrlEncodedContent content)
            {
                this.baseAddr = baseAddr;
                this.auth = auth;
                this.content = content;
                this.path = path;
                this.isAuth = isAuth;
            }
    
            public override string GetResult()
            {
                string resultContent = string.Empty;
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseAddr);
                    if (isAuth)
                    {
                        client.DefaultRequestHeaders.Add("Authorization", auth);
                    }
                    var t = client.PostAsync(path, content);
                    t.Wait();
                    var result = t.Result;
                    resultContent = result.Content.ReadAsStringAsync().Result;
                }
                return resultContent;
            }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Text;
    
    namespace Tools.HttpClientHelper
    {
        /// <summary>
        /// 创建http请求对象的工厂类
        /// </summary>
        public class HttpFactory
        {
            /// <summary>
            /// 创建http请求对象
            /// </summary>
            /// <param name="method">get/post</param>
            /// <param name="baseAddr">请求的主机</param>
            /// <param name="auth">验证字符串</param>
            /// <param name="path">请求路径</param>
            /// <param name="isAuth">是否启用验证,get请求时为false</param>
            /// <param name="content">发送的数据,get请求时为null</param>
            /// <returns></returns>
            public AbsHttpHelper CreateHttpHelper(string method, string baseAddr, string auth, string path, bool isAuth, FormUrlEncodedContent content)
            {
                AbsHttpHelper helper = null;
                method = method.ToLower();
                switch (method)
                {
                    case "get":
                        helper = new GetHelper(baseAddr, auth, path);
                        break;
                    case "post":
                        helper = new PostHelper(baseAddr, auth, path, isAuth, content);
                        break;
                }
                return helper;
            }
        }
    }

    调用:

    HttpFactory httpFactory = new HttpFactory();
                AbsHttpHelper helper = httpFactory.CreateHttpHelper("get", baseAddr, "", path, false, null);
                string rs = helper.GetResult();

    注意,这里的post方法只支持表单的键值对提交,content 如下

                var content = new FormUrlEncodedContent(new[] {
                        new KeyValuePair<string, string>("apiCode", "GetUser"),
                        new KeyValuePair<string, string>("pCount", "10"),
                        new KeyValuePair<string, string>("pNum", "1")
                        });

    如果要传json,则需使用StringContent,如下:

    protected async Task SendMsgAsync(string touser, string msg)
            {
                string sendMsgPath = AppConfig.CreateConfig().sendMsgPath + AccessTokenJob.token; //发送的路径
                var msgObj = new { content = msg };
    
                var content = new
                {
                    touser = touser,
                    msgtype = "text",
                    AppConfig.CreateConfig().agentid,
                    text = msgObj,
                    safe = 0
                };
                var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(content);
                StringContent contentStr = new StringContent(jsonStr);
                using (HttpClient client = new HttpClient())
                {
                    var respMsg = await client.PostAsync(sendMsgPath, contentStr);
                    string msgBody = await respMsg.Content.ReadAsStringAsync();
                }
            }
  • 相关阅读:
    [毕业设计]多文档自动摘要.面向灾害事件
    windows,无法启动承载网络,解决办法
    【现代程序设计】【期末作业】【homework-09】
    ColorNote.疑难解答
    【现代程序设计】【homework-08】
    【现代程序设计】【homework-07】
    【现代程序设计】【homework-05】
    【现代程序设计】【homework-04】
    homework-10
    homework-06&homework-09
  • 原文地址:https://www.cnblogs.com/SasaL/p/11155614.html
Copyright © 2011-2022 走看看