zoukankan      html  css  js  c++  java
  • C# 调用HTTP接口两种方式Demo

    本Demo大部分参考原著:http://www.jianshu.com/p/cfdaf6857e7e

    在WebApi发布之前,我们都是通过WebRequest/WebResponse这两个类组合来调用HTTP接口的

    封装一个RestClient类

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Web;
    
    namespace WebApplication1
    {
        public class RestClient
        {
            private string BaseUri;
            public RestClient(string baseUri)
            {
                this.BaseUri = baseUri;
            }
    
            #region Get请求
            public string Get(string uri)
            {
                //先根据用户请求的uri构造请求地址
                string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
                //创建Web访问对  象
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                //通过Web访问对象获取响应内容
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(),Encoding.UTF8);
                //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
                string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                reader.Close();
                myResponse.Close();
                return returnXml;
            }
            #endregion
    
            #region Post请求
            public string Post(string data, string uri)
            {
                //先根据用户请求的uri构造请求地址
                string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
                //创建Web访问对象
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                //把用户传过来的数据转成“UTF-8”的字节流
                byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
    
                myRequest.Method = "POST";
                myRequest.ContentLength = buf.Length;
                myRequest.ContentType = "application/json";
                myRequest.MaximumAutomaticRedirections = 1;
                myRequest.AllowAutoRedirect = true;
                //发送请求
                Stream stream = myRequest.GetRequestStream();
                stream.Write(buf,0,buf.Length);
                stream.Close();
    
                //获取接口返回值
                //通过Web访问对象获取响应内容
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
                string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                reader.Close();
                myResponse.Close();
                return returnXml;
    
            }
            #endregion
    
            #region Put请求
            public string Put(string data, string uri)
            {
                //先根据用户请求的uri构造请求地址
                string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
                //创建Web访问对象
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                //把用户传过来的数据转成“UTF-8”的字节流
                byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
    
                myRequest.Method = "PUT";
                myRequest.ContentLength = buf.Length;
                myRequest.ContentType = "application/json";
                myRequest.MaximumAutomaticRedirections = 1;
                myRequest.AllowAutoRedirect = true;
                //发送请求
                Stream stream = myRequest.GetRequestStream();
                stream.Write(buf, 0, buf.Length);
                stream.Close();
    
                //获取接口返回值
                //通过Web访问对象获取响应内容
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
                string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                reader.Close();
                myResponse.Close();
                return returnXml;
    
            }
            #endregion
    
    
            #region Delete请求
            public string Delete(string data, string uri)
            {
                //先根据用户请求的uri构造请求地址
                string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
                //创建Web访问对象
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
                //把用户传过来的数据转成“UTF-8”的字节流
                byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
    
                myRequest.Method = "DELETE";
                myRequest.ContentLength = buf.Length;
                myRequest.ContentType = "application/json";
                myRequest.MaximumAutomaticRedirections = 1;
                myRequest.AllowAutoRedirect = true;
                //发送请求
                Stream stream = myRequest.GetRequestStream();
                stream.Write(buf, 0, buf.Length);
                stream.Close();
    
                //获取接口返回值
                //通过Web访问对象获取响应内容
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                //通过响应内容流创建StreamReader对象,因为StreamReader更高级更快
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                //string returnXml = HttpUtility.UrlDecode(reader.ReadToEnd());//如果有编码问题就用这个方法
                string returnXml = reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
                reader.Close();
                myResponse.Close();
                return returnXml;
    
            }
            #endregion
        }
    }

    在Web API发布的同时,.NET提供了两个程序集:System.Net.HttpSystem.Net.Http.Formatting。这两个程序集中最核心的类是HttpClient

    以前的用法:创建一个控制台程序,测试HTTP接口的调用。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using WebApplication1;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                RestClient client = new RestClient("http://localhost:2444/");
                string result =  client.Get("api/Values");
                Console.WriteLine(result);
                Console.ReadKey();
            }
        }
    }

    .NET提供了两个程序集:System.Net.HttpSystem.Net.Http.Formatting。这两个程序集中最核心的类是HttpClient。在.NET4.5中带有这两个程序集,而.NET4需要到Nuget里下载Microsoft.Net.Http和Microsoft.AspNet.WebApi.Client这两个包才能使用这个类,更低的.NET版本就只能表示遗憾了只能用WebRequest/WebResponse或者WebClient来调用这些API了。

    //控制台代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Formatting;
    using System.Net.Http.Headers;
    using System.Text;
    using System.Threading.Tasks;
    using WebApplication1;
    using WebApplication1.Models;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                //RestClient client = new RestClient("http://localhost:2444/");
                //string result =  client.Get("api/Values");
                //Console.WriteLine(result);
                //Console.ReadKey();
    
                var client = new HttpClient();
                //基本的API URL
                client.BaseAddress = new Uri("http://localhost:2444/");
                //默认希望响应使用Json序列化(内容协商机制,我接受json格式的数据)
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //运行client接收程序
                Run(client);
                Console.ReadLine();
            }
            
            //client接收处理(都是异步的处理)
            static async void Run(HttpClient client)
            {          
                //post 请求插入数据
                var result = await AddPerson(client);
                Console.WriteLine($"添加结果:{result}"); //添加结果:true
    
                //get 获取数据
                var person = await GetPerson(client);
                //查询结果:Id=1 Name=test Age=10 Sex=F
                Console.WriteLine($"查询结果:{person}");
    
                //put 更新数据
                result = await PutPerson(client);
                //更新结果:true
                Console.WriteLine($"更新结果:{result}");
    
                //delete 删除数据
                result = await DeletePerson(client);
                //删除结果:true
                Console.WriteLine($"删除结果:{result}");
            }
    
            //post
            static async Task<bool> AddPerson(HttpClient client)
            {
                //向Person发送POST请求,Body使用Json进行序列化
                
                return await client.PostAsJsonAsync("api/Person", new Person() { Age = 10, Id = 1, Name = "test", Sex = "F" })
                                    //返回请求是否执行成功,即HTTP Code是否为2XX
                                    .ContinueWith(x => x.Result.IsSuccessStatusCode);
            }
    
            //get
            static async Task<Person> GetPerson(HttpClient client)
            {
                //向Person发送GET请求
                return await await client.GetAsync("api/Person/1")
                                         //获取返回Body,并根据返回的Content-Type自动匹配格式化器反序列化Body内容为对象
                                         .ContinueWith(x => x.Result.Content.ReadAsAsync<Person>(
                        new List<MediaTypeFormatter>() {new JsonMediaTypeFormatter()/*这是Json的格式化器*/
                                                        ,new XmlMediaTypeFormatter()/*这是XML的格式化器*/}));
            }
    
            //put
            static async Task<bool> PutPerson(HttpClient client)
            {
                //向Person发送PUT请求,Body使用Json进行序列化
                return await client.PutAsJsonAsync("api/Person/1", new Person() { Age = 10, Id = 1, Name = "test1Change", Sex = "F" })
                                    .ContinueWith(x => x.Result.IsSuccessStatusCode);  //返回请求是否执行成功,即HTTP Code是否为2XX
            }
            //delete
            static async Task<bool> DeletePerson(HttpClient client)
            {
                return await client.DeleteAsync("api/Person/1") //向Person发送DELETE请求
                                   .ContinueWith(x => x.Result.IsSuccessStatusCode); //返回请求是否执行成功,即HTTP Code是否为2XX
            }
    
        }
    }

    这个例子就是控制台通过HttpClient这个类调用WebApi中的方法,WebApi就是项目新创建的ValuesController那个控制器,什么都没动,测试结果如下:

  • 相关阅读:
    Redis设置生存时间或过期时间的相关命令
    .Net Core使用Redis
    Redis的数据类型
    Java集合 使用Collections
    Java集合 使用Iterator
    Java集合 使用Stack
    响应式常用样式汇总
    图片 文字 背景等响应式设置总结
    微信动态聊天工具
    第2章 栅格系统
  • 原文地址:https://www.cnblogs.com/BOSET/p/7089284.html
Copyright © 2011-2022 走看看