C#_winfrom与API之HttpClient

似水流年梦 2020-01-12

最近需要写一些winfrom与端口交互的代码,需要的自取哦!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsApplication7
{
    public static class HTTPClientHelper
    {
        //TCP/IP 3次握手
        //第1个参数是请求类型,第2个参数是API方法名,第3个参数是传送的对象
        public static string GetAPIData(string requestType, string actionname, object obj = null)
        {
            //实例化HttpClient
            HttpClient hc = new HttpClient();
            //设置API地址
            hc.BaseAddress = new Uri("http://localhost:12617/api/default/");

            //创建一个任务获取服务端返回的结果
            Task<HttpResponseMessage> task = null;
            //第1次握手发送请求
            switch (requestType)
            {
                case "get":
                    task = hc.GetAsync(actionname);
                    break;
                case "post":
                    task = hc.PostAsJsonAsync(actionname, obj);
                    break;
                case "put":
                    task = hc.PutAsJsonAsync(actionname, obj);
                    break;
                case "delete":
                    task = hc.DeleteAsync(actionname);
                    break;
            }
            //第2次握手 接收数据
            if (task != null)
            {
                //第3次握手 检查数据包
                if (task.Result.IsSuccessStatusCode)
                {
                    //把XML转换为字符串
                    var strtask = task.Result.Content.ReadAsStringAsync();
                    //转换结果
                    return strtask.Result;
                }
            }
            return "";
        }


    }


}

相关推荐

nalanrumeng / 0评论 2020-04-09