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)
{
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;
}
}