问题描述
我需要在Xamarin中填写输入内容的表单,然后将其发送到我的API页面。
我已经尝试过在“邮递员”中发送数据并正确保存了数据,但是我想知道如何从Xamarin发送数据。
注意,我可以从应用程序正确读取数据。
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; }
}
您在Xamarin中创建的表单就是这个。
<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"/>
解决方法
这是我用于API的静态类。如果只有一个,则可以更改该URL以使其与您的URL匹配。确保逐步检查并确认所有“ /”都在正确的位置!
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
}
}