本身積累寫的winfrom 操做api 類

引用 類json

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 方法api

 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> 泛型集合,在後臺獲取時聲明泛型收集便可.app

api 在winfrom 中的put 方法async

 

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 方法url

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 方法spa

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 方法進行修改code

相關文章
相關標籤/搜索