發送POST請求
/// <summary>
/// API發送POST請求
/// </summary>
/// <param name="url">請求的API地址</param>
/// <param name="parametersJson">POST過去的參數(JSON格式)字符串</param>
/// <returns></returns>
public static string ApiPost(string url, string parametersJson)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["ApiHttp"]);
// 為JSON格式添加一個Accept報頭
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//需要傳遞的參數(參數封裝成JSON)
HttpContent content = new StringContent(parametersJson)
{
Headers = { ContentType = new MediaTypeHeaderValue("application/json") }
};
HttpResponseMessage response = client.PostAsync(url, content).Result;
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync().Result;
}
發送GET請求
/// <summary>
/// API發送GET請求,返回Json
/// </summary>
/// <param name="url"></param>
/// <returns>如果未成功返回空</returns>
public static string ApiGet(string url)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["ApiHttp"]);
// 為JSON格式添加一個Accept報頭
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(url).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsStringAsync().Result;
}
return "";
}
發送DELETE請求
/// <summary>
/// API發送DELETE請求,返回狀態:200成功,201失敗
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string ApiDelete(string url)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["ApiHttp"]);
// 為JSON格式添加一個Accept報頭
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.DeleteAsync(url).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsStringAsync().Result;
}
return "";
}
