c#后端调用webapi的方法

最近因为后端需要调用webapi接口,因此写了一个通用接口,如下:

private static async Task<bool> InvokeWebapi(string url, string api, string type, Dictionary<string, string> dics)
{

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("authorization", "Basic YWRtaW46cGFzc3dvcmRAcmljZW50LmNvbQ==");//basic编码后授权码

//client.DefaultRequestHeaders.Add();
client.BaseAddress = new Uri(url);

client.Timeout = TimeSpan.FromSeconds(510);
string result = "";
if (type.ToLower() == "put")
{
HttpResponseMessage response;
//包含复杂类型
if (dics.Keys.Contains("input"))
{
if (dics != null)
{
foreach (var item in dics.Keys)
{
api = api.Replace(item, dics[item]).Replace("{", "").Replace("}", "");
}
}
var contents = new StringContent(dics["input"], Encoding.UTF8, "application/json");
response = client.PutAsync(api, contents).Result;
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
return true;
}
return false;
}

var content = new FormUrlEncodedContent(dics);
response = client.PutAsync(api,content).Result;
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
return true;
}
}
else if (type.ToLower() == "post")
{
var content = new FormUrlEncodedContent(dics);

HttpResponseMessage response = client.PostAsync(api, content).Result;
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
return true;
}
}
else if (type.ToLower() == "get")
{
HttpResponseMessage response = client.GetAsync(api).Result;

if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
return true;
}
}
else
{
return false;
}
return false;
}

猜你喜欢

转载自www.cnblogs.com/wutongcoding/p/11512282.html