Reputation: 11
I need to fill a form with inputs in Xamarin, and send them to my API page.
I already tried sending the data in "Postman" and it saved it correctly, but I would like to know how to send it from Xamarin.
Attention, I can read the data correctly from the application.
public class FuelPurchase
{
public int id { get; set; }
public string date{ get; set; }
public int vueltametal { get; set; }
public int amount{ get; set; }
public string station{ get; set; }
public string location{ get; set; }
}
And the form you create in Xamarin is this.
<Label Text="Fuel Purchase"/>
<Label Text="Fecha">
<DatePicker x:Name="Date"/>
<Label Text="Station"/>
<Entry x:Name="Station"/>
<Label Text="Location"/>
<Entry x:Name="Location"/>
<Label Text="Amount"/>
<Entry x:Name="amount" Keyboard="Numeric"/>
Upvotes: 0
Views: 56
Reputation: 80
Here is a static class that I use for API's. You can change the url to match yours if you only have one. Make sure to step through it and check that all of your "/"'s are in the right spot!
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using NGJS = System.Text.Json;
using System.Threading.Tasks;
namespace TestBCS
{
public class RestService
{
readonly HttpClient client;
public RestService()
{
client = new HttpClient(new HttpClientHandler
{
Proxy = null,
UseProxy = false
});
}
#region GET
public async Task<object> RefreshDataAsync(string url, string qs)
{
Uri uri = new Uri(string.Format(url, qs));
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
using (var stream = await response.Content.ReadAsStreamAsync())
{
return await NGJS.JsonSerializer.DeserializeAsync<object>(stream);
}
}
//Error Handling here
return null;
}
#endregion
#region POST
static void SerializeJsonIntoStream(object value, Stream stream)
{
using (var sw = new StreamWriter(stream, new UTF8Encoding(false), 1024, true))
using (var jtw = new JsonTextWriter(sw) { Formatting = Formatting.None })
{
var js = new JsonSerializer();
js.Serialize(jtw, value);
jtw.Flush();
}
}
HttpContent CreateHttpContent(object content)
{
HttpContent httpContent = null;
if (content != null)
{
var ms = new MemoryStream();
SerializeJsonIntoStream(content, ms);
ms.Seek(0, SeekOrigin.Begin);
httpContent = new StreamContent(ms);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
return httpContent;
}
public async Task PostStreamAsync(string url, object content)
{
string Url = url;
using (var client = new HttpClient())
using (var request = new HttpRequestMessage(HttpMethod.Post, Url))
using (var httpContent = CreateHttpContent(content))
{
request.Content = httpContent;
using (var response = await client
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
.ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
Debug.WriteLine("Successfully Sent");
}
}
}
#endregion
}
}
Upvotes: 1