zoukankan      html  css  js  c++  java
  • 调用webApi封装

     /// <summary>
            /// 调用Api(Post请求)
            /// </summary>
            /// <param name="url">api地址</param>
            /// <param name="body">参数</param>
            /// <returns></returns>
            public ResponseEntity HttpApiPost(string url, string body)
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Accept = "text/html, application/xhtml+xml, */*";
                request.ContentType = "application/json";
                ResponseEntity responseEntity = null;
                string responseString = string.Empty;
                try
                {
                    byte[] buffer = encoding.GetBytes(body);
                    request.ContentLength = buffer.Length;
                    request.GetRequestStream().Write(buffer, 0, buffer.Length);
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        responseString = reader.ReadToEnd();
                        if (!string.IsNullOrEmpty(responseString))
                        {
                            responseEntity = JsonConvert.DeserializeObject<ResponseEntity>(responseString);
                        }
                        else
                        {
                            LogUtils.error($"调用DB服务(Post请求)返回的消息为空,Url为:{url}");
                        }
                    }
                }
                catch (Exception exception)
                {
                    LogUtils.error($"调用DB服务(Get请求)发生异常,Url为:{url},返回的消息为:{responseString}", exception);
                }
                return responseEntity;
            }
  • 相关阅读:
    解决Tomcat9打印台乱码问题
    分治思想与归并排序
    linux下libuv库安装教程
    Linux init
    栈和堆上的内存分配和回收
    Python帮助文档中Iteration iterator iterable 的理解
    Qt基本框架介绍
    PyQt5+Python3.5.2-32bit开发环境搭建
    常用网站
    [Repost]Events and Signals in PyQt4
  • 原文地址:https://www.cnblogs.com/yuanshuo/p/14690902.html
Copyright © 2011-2022 走看看