Post json到xamarin web客户端api
本文关键字:客户端 api web xamarin json Post | 更新日期: 2023-09-27 18:13:43
我想发布一个jsonobject到我的webapi。使用正常的c#代码,我会在我的httpClient对象上使用PostAsJsonAsync。但xamarin似乎并不支持这一点。所以我的问题是我如何张贴json到我的api使用xamarin webclient或webrequest?
这是我的代码现在返回null…
protected async override void OnResume()
{
base.OnResume();
var clientRequest = new ResourceByNameRequest
{
Name = "G60",
UserId = "1"
};
HttpContent myContent = new StringContent(clientRequest.ToString());
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("XXX");
var cancellationToken = new CancellationToken();
var response = client.PostAsync("/api/Resource/ResourceByName", myContent, cancellationToken).Result;
var result = await response.Content.ReadAsStreamAsync();
//return result;
}
}
catch (Exception)
{
throw;
}
}
试试这样:
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//...
protected override void OnResume()
{
var request = HttpWebRequest.Create("Your_URL_XXX");
request.ContentType = "application/json";
request.Method = "POST";
var clientRequest = new ResourceByNameRequest
{
Name = "G60",
UserId = "1"
};
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(clientRequest.ToString());
}
try
{
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
string error = "";
if (response.StatusCode != HttpStatusCode.OK)
error = string.Format("Error fetching data. Server returned status code: {0} | Description: {1}", response.StatusCode, response.StatusDescription);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
if (string.IsNullOrWhiteSpace(content))
{
strResponse = "Response contained empty body...";
}
else
{
var cont = JObject.Parse(content);
YOUR_OBJECT_RESPONSE.PROP1 = cont["Prop1"].NullSafeToString();
YOUR_OBJECT_RESPONSE.PROP2 = cont["Prop2"].NullSafeToString();
//...
}
}
}
}
catch (WebException wex)
{
var pageContent = new StreamReader(wex.Response.GetResponseStream()).ReadToEnd();
}
}