自己积累写的winfrom 操作api 类

引用 类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using Newtonsoft.Json;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Windows.Forms;

  api 在winform中的get 方法

 public static List<T> Jsonobject<T>(Uri url)
        {

            using (var client = new HttpClient())
            {
                var result = client.GetStringAsync(url).Result;
                
                List<T> ds = JsonConvert.DeserializeObject<List<T>>(result);
                return ds;
            }

我在这里返回的是List<T> 泛型集合,在后台获取时声明泛型收集即可.

api 在winfrom 中的put 方法

 

public async void PueAnsy<T>(Uri uri, T t1)
        {

            string data = JsonConvert.SerializeObject(t1);
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms, t1);
            ms.Position = 0;
            HttpContent content = new StreamContent(ms);
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            HttpClient client = new HttpClient();
            HttpResponseMessage response = await client.PutAsync(uri, content);
if (response.IsSuccessStatusCode) { } else { } }

api 在winfrom 中的Post 方法

public async void Update<T>(T t1, Uri url)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            serializer.WriteObject(ms, t1); //传入model

            ms.Position = 0;
            HttpContent content = new StreamContent(ms);//将MemoryStream转成HttpContent
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            HttpClient client = new HttpClient();
            HttpResponseMessage response = await client.PostAsync(url, content); 

if (response.IsSuccessStatusCode) { MessageBox.Show("成功"); } }

api 在winfrom 中的Delete 方法

public async void Delete(Uri url)
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage response = await client.DeleteAsync(url);
            if (response.IsSuccessStatusCode)
            {
                MessageBox.Show("删除成功");
            }
            else
            {
                MessageBox.Show("删除失败");
            }
        }

如果delete方法 需要传入model ,参照update 方法进行修改

 

转载于:https://www.cnblogs.com/zhoudidi/p/6676768.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值