zoukankan      html  css  js  c++  java
  • HTTPClick调用WebApi帮助类

    1、创建ApiHelper类

    2、复制以下代码到类中

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace 对应的命名空间
    {
        public class ApiHelper
        {
            /// <summary>
            /// api调用方法
            /// </summary>
            /// <param name="controllerName">控制器名称</param>
            /// <param name="overb">请求方式</param>
            /// <param name="action">方法名称</param>
            /// <param name="obj">方法参数</param>
            /// <returns>json字符串</returns>
            public static string GetApiMethod(string controllerName, string overb, string action, object obj = null)
            {
                Task<HttpResponseMessage> task = null;
                string json = "";
                //创建一个Http客户端对象
                HttpClient client = new HttpClient();
                //指定访问WebApi的uri地址
                client.BaseAddress = new Uri("http://localhost:47369/api/" + controllerName + "/");
                /*根据不同的动作执行不同的方法*/
                switch (overb)
                {
                    case "get":
                        task = client.GetAsync(action);
                        break;
                    case "post":
                        task = client.PostAsJsonAsync(action, obj);
                        break;
                    case "delete":
                        task = client.DeleteAsync(action);
                        break;
                    case "put":
                        task = client.PutAsJsonAsync(action, obj);
                        break;
                    default:
                        break;
                }
                //等待请求的过程
                task.Wait();
                //接收响应的结果
                var response = task.Result;
                //判断响应的状态码是成功时候
                if (response.IsSuccessStatusCode)
                {
                    //从响应对象的内容中读取字符串
                    var read = response.Content.ReadAsStringAsync();
                    //等待读取的过程
                    read.Wait();
                    //接收读取的结果-json
                    json = read.Result;
                }
                return json;
            }
        }
    }
         
     
     
    View Code

    3、修改命名空间

    4、成功调用

  • 相关阅读:
    selenium执行js代码的两个方法
    PostgresSQL数据库安装及操作
    [Python]requests使用代理
    linux下postgreSQL初始化设置方法
    如何用Jenkins自动化部署项目(教程,从零到搭建完成)
    Python笔记:Geopython GIS相关库
    Postman接口&压力测试
    python+django+vue实现前后端分离项目和部署的操作
    python-Django-1.8.2中文文档
    CSS详细解读定位
  • 原文地址:https://www.cnblogs.com/yu-shang/p/10644375.html
Copyright © 2011-2022 走看看