C# Post方法

C# Post方法封装


    public static async Task MyPost<T>(T t,string url)
    {
       HttpClient client = new HttpClient();
       client.BaseAddress = new Uri("http://test.com");
       Dictionary<string, string> dic = new Dictionary<string, string>();
       getProperties(t, dic);
       HttpContent content = new FormUrlEncodedContent(dic);
       HttpResponseMessage response = await client.PostAsync(url, content);
       string message = await response.Content.ReadAsStringAsync();
    }

    public static string getProperties<T>(T t,Dictionary<string,string> myDic)
    {
        string tStr = string.Empty;
        if (t == null)//判空
        {
            return tStr;
        }
        PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
        if (properties.Length <= 0)//属性个数是否为0
        {
            return tStr;
        }
        foreach (PropertyInfo item in properties)
        {
            string name = item.Name;
            object value = item.GetValue(t, null);
            if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
            {
                myDic.Add(name, value.ToString());
            }
        }
        return tStr;
    }





 class Test1
    {
        public string s1 { get; set; }
        public string s2 { get; set; }
        public float f1 { get; set; }
        public int i1 { get; set; }

        public Test1(string s1, string s2, float f1, int i1)
        {
            this.s1 = s1;
            this.s2 = s2;
            this.f1 = f1;
            this.i1 = i1;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值