使用httpClient 调用get,Post接口

1.httpClient 调用get接口

private async Task<IList<(int columnId, string columnName)>> GetFunction(int id)
{
var client = new HttpClient { BaseAddress = new Uri(BasicUrl) };
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await client.GetAsync($"/xxxx/xxxxxxx/Function?id={id}");
if (!response.IsSuccessStatusCode) throw new Exception("");
var json = await response.Content.ReadAsStringAsync();
var jObj = JsonConvert.DeserializeObject<JObject>(json);
return ((JArray) ((JObject)jObj["Data"])["ColumnConfigs"]).Select(i =>
{
var column = (JObject) i;
return (column["id"].Value<int>(), column["ColumnName"].Value<string>());
}).ToList();
}

2.httpClient 调用Post接口

 private async Task SaveData(int tableId, IList<List<(int columnId, string columnValue)>> rows )

{
var client = new HttpClient { BaseAddress = new Uri(BasicUrl) };
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var json = JsonConvert.SerializeObject(new
{
PkId = tableId.ToString(),
Data = data
});
var response = await client.PostAsync("/xxxx/xxx/Save", new StringContent(json, Encoding.UTF8, "application/json"));

var error = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode) throw new Exception("");
}

原文地址:https://www.cnblogs.com/xiaohouye/p/11381524.html