c# get post put delete接口

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
}

}

以前的调用方法:
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
    }

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值