C# API POST与GET的调用

C# API POST与GET的调用

WebClient与HttpWebRequest HttpClient没测试

WebClient与HttpWebRequest还有HttpClient的区别

继承关系

Object --> MarshalByRefObject --> Component --> WebClient
提供用于将数据发送到由 URI 标识的资源及从这样的资源接收数据的常用方法。

Object --> MarshalByRefObject --> WebRequest --> HttpWebRequest
提供 WebRequest 类的 HTTP 特定的实现。

Object --> HttpMessageInvoker --> HttpClient
用于发送 HTTP 请求并从 URI 标识的资源接收 HTTP 响应。

从继承关系上来看 WebClient要比HttpWebRequest要高一层,HttpClient和其他两个基本关系不大
从介绍上来看 HttpClient是针对Http的请求,而其他两个是针对URI的资源请求和接收

使用关系

WebClient是一种更高级别的抽象,是HttpWebRequest为了简化最常见任务而创建的,使用过程中你会发现他缺少基本的header,timeoust的设置,不过这些可以通过继承httpwebrequest来实现。相对来说,WebClient比WebRequest更加简单,它相当于封装了request和response方法,不过需要说明的是,Webclient和WebRequest继承的是不同类,两者在继承上没有任何关系。使用WebClient可能比HttpWebRequest直接使用更慢(大约几毫秒),但却更为简单,减少了很多细节,代码量也比较少。

HttpWebRequest 这是.NET创建者最初开发用于使用HTTP请求的标准类。使用HttpWebRequest可以让开发者控制请求/响应流程的各个方面,如 timeouts, cookies, headers, protocols。另一个好处是HttpWebRequest类不会阻塞UI线程。例如,当您从响应很慢的API服务器下载大文件时,您的应用程序的UI不会停止响应。HttpWebRequest通常和WebResponse一起使用,一个发送请求,一个获取数据。HttpWebRquest更为底层一些,能够对整个访问过程有个直观的认识,但同时也更加复杂一些。

HttpClient是.NET4.5引入的一个HTTP客户端库,其命名空间为 System.Net.Http ,.NET 4.5之前我们可能使用WebClient和HttpWebRequest来达到相同目的。HttpClient利用了最新的面向任务模式,使得处理异步请求非常容易。它适合用于多次请求操作,一般设置好默认头部后,可以进行重复多次的请求,基本上用一个实例可以提交任何的HTTP请求。HttpClient有预热机制,第一次进行访问时比较慢,所以不应该用到HttpClient就new一个出来,应该使用单例或其他方式获取HttpClient的实例.

代码示例

namespace API读取写入程序
{
    public class HttpHelper
    {

        /// <summary>
        /// 使用 POST 方法将指定的字符串上载到指定的资源
        /// </summary>
        /// <param name="address">接收字符串的资源的 URI</param>
        /// <param name="data">上载的字符串</param>
        /// <returns></returns>
        public static string Post_WebClient(string address, string data = "")
        {
            //初始化配置
            WebClient client = new WebClient();
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers.Add("Channel", "1102");
            //添加防止乱码
            client.Encoding = Encoding.UTF8;
            string result = client.UploadString(address, data);
            //返回数据
            return result;
        }

        /// <summary>
        ///  使用 GET 方法下载请求的资源
        /// </summary>
        /// <param name="address">要下载的 URI 的数据</param>
        /// <returns></returns>
        public static string Get_WebClient(string address)
        {
            //初始化配置
            WebClient client = new WebClient();
            //添加防止乱码
            client.Encoding = Encoding.UTF8;
            string result = client.DownloadString(address);
            //返回数据
            return result;
        }

        /// <summary>
        /// 带超时的Post发送Json,实现超时重发,启用接口日志
        /// </summary>
        /// <param name="address">地址</param>
        /// <param name="data">Json字符串</param>
        /// <param name="encoding">编码类型</param>
        /// <param name="timeout">超时时间</param>
        /// <returns></returns>
        public static string Post_HttpWebRequest(string address, string data, Encoding encoding, int timeout)
        {
            //初始化配置
            HttpWebRequest tmpRequest = (HttpWebRequest)WebRequest.Create(address);
            tmpRequest.Method = "POST";
            tmpRequest.KeepAlive = false;
            tmpRequest.Timeout = timeout;
            tmpRequest.ContentType = "application/json";
            byte[] tmpBts = encoding.GetBytes(data);
            tmpRequest.ContentLength = tmpBts.Length;
            //提交数据
            Stream tmpRequestStream = tmpRequest.GetRequestStream();
            tmpRequestStream.Write(tmpBts, 0, tmpBts.Length);
            tmpRequestStream.Flush();
            //接收数据  
            HttpWebResponse tmpResponse = (HttpWebResponse)tmpRequest.GetResponse();
            Stream tmpResponseStream = tmpResponse.GetResponseStream();
            StreamReader tmpStreamReader = new StreamReader(tmpResponseStream, encoding);
            string retString = tmpStreamReader.ReadToEnd();
            //关闭
            tmpStreamReader.Close();
            tmpResponseStream.Close();
            tmpRequestStream.Close();
            //返回数据
            return retString;
        }

        internal static string Post_WebClient(string servPath, object value)
        {
            throw new NotImplementedException();
        }
    }
    public interface IBusiness
    {
        public (bool bResult, string strErrMsg) Login(string account, string password);
    }
    public class Business : IBusiness
    {
        public (bool bResult, string strErrMsg) Login(string username, string password)
        {
            try
            {
                //定义传输的json
                JObject jo = new JObject();
                jo.Add("channel", channel);
                jo.Add("libCode", libCode);
                jo.Add("number", number);
                jo.Add("totalNum", totalNum);
                string servPath = @$"http://192.168.1.253:7072/platform/token/login";
                //API操作
                string result = HttpHelper.Post_WebClient(servPath, jo.ToString());
                jo = JObject.Parse(result);
                bool bRes = (bool)jo["success"];
                //返回值 赋值与操作
                if (bRes)
                {
                    if (string.IsNullOrEmpty(jo["data"].ToString()))
                    {

                    }
                }
                return (bRes, jo["message"].ToString());
            }
            catch (Exception ex)
            {
                return (false, ex.Message);
            }
        }
    }
}

总结

以上就是这次的总结了,后面在进行整理.

2022/11/1

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值