zoukankan      html  css  js  c++  java
  • 用Web API Client 调用 Web API

    安装Web API客户端库

    右键单击项目,选择管理 NuGet程序包,选择联机选项,选择全部,在搜索框中输入“Microsoft.AspNet.WebApi.Client”,

    搜索结果就是要安装的类库,单击安装到完成。NuGet会自动添加引用

     需要引入的命名空间:

    using System.Net.Http;
    using System.Net.Http.Headers;

    Get调用

    HttpClient初始化
     HttpClient client = new HttpClient();
     client.BaseAddress = new Uri("http://localhost:9000/"); 
     // Add an Accept header for JSON format.
     // 为JSON格式添加一个Accept报头
     client.DefaultRequestHeaders.Accept.Add( 
                    new MediaTypeWithQualityHeaderValue("application/json")); 
    var response = client.GetAsync("api/GetEmployees").Result; //转换为同步方法

    response 中可以直接拿到http请求状态。

    if (response.IsSuccessStatusCode) //请求成功
    { 
       //从方法名中可以看出是异步调用,取Result后,就变成同步了,
        var results = response.Content.ReadAsAsync<IEnumerable<Employee>>().Result; 
        foreach (var p in results) 
        { 
            Console.WriteLine("{0}	{1};	{2}", p.Name, p.Age, p.Sex); 
        } 
    } 
    else 
    { 
        Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); 
    }

     

    Post调用

    using System.Net.Http;
    using System.Net.Http.Headers;
    
    //api 为  http://localhost:8000/Employee/Update
      //传入参数 name,age,sex
            HttpClient client = new HttpClient();
            public override bool SendMessage()
            {
                client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));
             
                var paras= new { name ="", age =10,sex="" };
                try
                {
                    var response = client.PostAsJsonAsync(" http://localhost:8000/Employee/Update", paras).Result;
                     //如果调用失败,抛出异常
                    response.EnsureSuccessStatusCode();
                    if (response.IsSuccessStatusCode)
                    {
                        var result = response.Content.ReadAsStringAsync();
                       
                      //result.Result 是一个json字符串,解析后就可以拿到调用后的返回值
                        return false;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                
                    return false;
                }
            
                return true;
            }
    
    
        

    put,和delete方法调用同post类似,在此不再介绍。

  • 相关阅读:
    NoSQL之Redis入门笔记
    运维甩锅神器---Jumpserver
    sersync+rsync=实时异步备份
    gitlab+jenkins=自动化构建
    python笔记07-----打包模块(shutil,zipfile,tarfile)
    python笔记06-----常用模块(time,os,sys,random)
    python笔记09-----装饰器,生成器,迭代器
    python笔记05-----函数
    机器学习3_EM算法与混合高斯模型
    机器学习2-极大似然估计与贝叶斯估计
  • 原文地址:https://www.cnblogs.com/langhua/p/4238251.html
Copyright © 2011-2022 走看看