呼叫WebAPI
取得資料 (使用HttpClient)
var uri = "https://api.domain.com/v1/products/1";
HttpClient _httpClient = new HttpClient();
public async Task<IEnumerable<Person>> GetPeople()
{
var result = await _httpClient.GetAsync(BASE_URI);
var peopleJson = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<IEnumerable<Person>>(peopleJson);
}
上傳資料
public async Task<bool> CreatePerson(Person person)
{
var personJson = JsonConvert.SerializeObject(person);
var content = new StringContent(personJson, Encoding.UTF8, "application/json");
//add a header
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "my_access_token");
client.Headers.Add("key", "value"); // For any other types of headers.
var result = await _httpClient.PostAsync(BASE_URI, content);
return result.IsSuccessStatusCode;
}
useful links
https://mallibone.com/post/implementing-a-cross-platform-http-client-in-the-pcl-to-consume-your-aspnet-web-api-backend-on-azure
https://github.com/svswaminathan/xamarin-forms-httpclient-sample
https://brax.tv/platform/xamarin-forms/json-with-httpclient-and-json-net
https://xamarinhelp.com/connecting-remote-database-xamarin-forms/