传入参数转为Json
string parameters = JsonConvert.SerializeObject(parameters);
调用api
public bool Fetch(out string results, string url, string type = "GET", string parameters = "",
params KeyValuePair<string, string>[] headerParams)
{
try
{
using (HttpClient httpClient = new HttpClient {Timeout = TimeSpan.FromMinutes(30)})
{
HttpResponseMessage response = null;
foreach (var headerParam in headerParams)
{
httpClient.DefaultRequestHeaders.Add(headerParam.Key, headerParam.Value);
}
if ("POST".Equals(type, StringComparison.OrdinalIgnoreCase))
{
HttpContent httpContent = new StringContent(parameters);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response = httpClient.PostAsync(url, httpContent).Result;
}
else if ("GET".Equals(type, StringComparison.OrdinalIgnoreCase))
{
response = httpClient.GetAsync(url).Result;
}
if (response == null || !response.IsSuccessStatusCode)
{
results = response?.StatusCode.ToString();
return false;
}
results = response.Content.ReadAsStringAsync().Result;
}
}
catch (Exception exception)
{
results = exception.Message;
return false;
}
return true;
}