簡易 HttpClient Post泛型請求
我們使用httpclient get or post
常常會想要紀錄log或是回傳exceptional或是做一些事情
發現一直在寫重複的東西 如果我們寫個泛型的靜態方法是不是就乾淨多了
class Program
{
static void Main(string[] args)
{
string url = "http://jsonplaceholder.typicode.com/posts";
var data = new PostModel();
data.title = "foo";
data.body = "bar";
data.userId = 1;
var c = HttpClient<PostModel, ResultModel>(url, data);
Console.WriteLine(JsonConvert.SerializeObject(c));
Console.Read();
}
/// <summary>
/// 如果沒有post參數的話
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="url"></param>
/// <returns></returns>
protected static TResult HttpClient<TResult>(string url) where TResult : class
{
return HttpClient<string, TResult>(url, string.Empty);
}
protected static TResult HttpClient<TPost, TResult>(string url, TPost PostData) where TResult : class where TPost : class
{
var client = new HttpClient();
var task = client.PostAsJsonAsync(url, PostData);
//10秒timeout
var hasimeOut = task.Wait(10000);
if (!hasimeOut)
{
Console.WriteLine("timeout了");
Console.Read();
}
var response = task.Result;
var jsonString = response.Content.ReadAsStringAsync();
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
};
//反序列
var Result = JsonConvert.DeserializeObject<TResult>(jsonString.Result);
return Result;
}
public class ResponseBase<TResult> {
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int Code { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string message { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public TResult data { get; set; }
}
public class PostModel
{
public string title { get; set; }
public string body { get; set; }
public int userId { get; set; }
}
public class ResultModel
{
public string title { get; set; }
public string body { get; set; }
public int userId { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string test { get; set; }
}
}