c#后端调用webapi的方法

 

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

 1  private static async Task<bool> InvokeWebapi(string url, string api, string type, Dictionary<string, string> dics)
 2  {
 3      HttpClient client = new HttpClient();
 4      client.DefaultRequestHeaders.Add("authorization", "Basic YWRtaW46cGFzc3dvcmRAY29tcGFueS5jb20=");//basic编码后授权码
 5 
 6      //client.DefaultRequestHeaders.Add();
 7      client.BaseAddress = new Uri(url);
 8 
 9      client.Timeout = TimeSpan.FromSeconds(510);
10      string result = "";
11      if (type.ToLower() == "put")
12      {
13          HttpResponseMessage response;
14          //包含复杂类型
15          if (dics.Keys.Contains("input"))
16          {
17              if (dics != null)
18              {
19                  foreach (var item in dics.Keys)
20                  {
21                      api = api.Replace(item, dics[item]).Replace("{", "").Replace("}", "");
22                  }
23              }
24              var contents = new StringContent(dics["input"], Encoding.UTF8, "application/json");
25              response = client.PutAsync(api, contents).Result;
26              if (response.IsSuccessStatusCode)
27              {
28                  result = await response.Content.ReadAsStringAsync();
29                  return true;
30              }
31              return false;
32          }
33 
34          var content = new FormUrlEncodedContent(dics);
35          response = client.PutAsync(api, content).Result;
36          if (response.IsSuccessStatusCode)
37          {
38              result = await response.Content.ReadAsStringAsync();
39              return true;
40          }
41      }
42      else if (type.ToLower() == "post")
43      {
44          var content = new FormUrlEncodedContent(dics);
45 
46          HttpResponseMessage response = client.PostAsync(api, content).Result;
47          if (response.IsSuccessStatusCode)
48          {
49              result = await response.Content.ReadAsStringAsync();
50              return true;
51          }
52      }
53      else if (type.ToLower() == "get")
54      {
55          HttpResponseMessage response = client.GetAsync(api).Result;
56 
57          if (response.IsSuccessStatusCode)
58          {
59              result = await response.Content.ReadAsStringAsync();
60              return true;
61          }
62      }
63      else
64      {
65          return false;
66      }
67      return false;
68  }

 


posted on 2019-09-12 15:49  桐舟共济  阅读(3636)  评论(0编辑  收藏  举报

导航