C# 调用HTTP接口两种方式Demo及示例代码

转载https://www.cnblogs.com/BOSET/p/7089284.html
本Demo大部分参考原著:http://www.jianshu.com/p/cfdaf6857e7e

在C#中,传统调用HTTP接口一般有两种办法

WebRequest/WebResponse组合的方法调用
WebClient类进行调用。
第一种方法抽象程度较低,使用较为繁琐;而WebClient主要面向了WEB网页场景,在模拟Web操作时使用较为方便,但用在RestFul场景下却比较麻烦,在Web API发布的同时,.NET提供了两个程序集:System.Net.Http和System.Net.Http.Formatting。这两个程序集中最核心的类是HttpClient。在.NET4.5中带有这两个程序集,而.NET4需要到Nuget里下载Microsoft.Net.Http和Microsoft.AspNet.WebApi.Client这两个包才能使用这个类,更低的.NET版本就只能表示遗憾了只能用WebRequest/WebResponse或者WebClient来调用这些API了。

在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.Http和System.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.Http和System.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那个控制器,什么都没动,测试结果如下:

  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#调用 AWS API 接口并使用 AWS 鉴权方式,可以通过 AWS SDK for .NET 来实现。以下是一个简单的示例: 1. 首先,需要安装 AWS SDK for .NET。可以通过 NuGet 包管理器来安装。 2. 在代码中引入 AWS SDK 的命名空间: ```csharp using Amazon; using Amazon.Runtime; using Amazon.Runtime.CredentialManagement; using Amazon.S3; using Amazon.S3.Model; ``` 3. 创建 AWS 访问凭证对象。可以使用以下代码从 AWS 访问密钥文件或凭证配置文件中读取访问密钥和秘密访问密钥: ```csharp var options = new CredentialProfileOptions { AccessKey = "YOUR_ACCESS_KEY", SecretKey = "YOUR_SECRET_KEY" }; var profile = new CredentialProfile("profile-name", options); var profileAWSCredentials = new CredentialProfileStoreChain().TryGetAWSCredentials(profile, out var awsCredentials); ``` 4. 创建 AWS S3 客户端对象,并使用上一步中创建的访问凭证对象进行身份验证: ```csharp var region = RegionEndpoint.GetBySystemName("us-west-2"); // 指定 AWS 区域 var s3Client = new AmazonS3Client(awsCredentials, region); ``` 5. 调用 AWS S3 API 接口。以下是一个示例: ```csharp var request = new PutObjectRequest { BucketName = "my-bucket", Key = "my-object", ContentBody = "Hello World!" }; var response = await s3Client.PutObjectAsync(request); ``` 以上代码演示了如何使用 AWS SDK for .NET 调用 AWS S3 API 接口并使用 AWS 鉴权方式进行身份验证。根据实际情况,需要将代码中的访问密钥和秘密访问密钥替换为自己的凭证信息,并将区域、桶名和对象键等参数替换为实际的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值