如何在c# Xamarin中从HTTP帖子中获取数据?
本文关键字:获取 数据 HTTP Xamarin 中从 | 更新日期: 2023-09-27 18:16:37
我正在尝试使用HTTPClient发布一些数据。当简单地以JSON格式获取数据时,我已经设法使用以下代码,但它似乎不适用于POST。
这是我使用的代码:
public static async Task<SwipeDetails> SaveSwipesToCloud()
{
//get unuploaded swips
IEnumerable<SwipeDetails> swipesnotsved = SwipeRepository.GetUnUploadedSwipes();
foreach (var item in swipesnotsved)
{
//send it to the cloud
Uri uri = new Uri(URL + "SaveSwipeToServer" + "?locationId=" + item.LocationID + "&userId=" + item.AppUserID + "&ebCounter=" + item.SwipeID + "&dateTimeTicks=" + item.DateTimeTicks + "&swipeDirection=" + item.SwipeDirection + "&serverTime=" + item.IsServerTime );
HttpClient myClient = new HttpClient();
var response = await myClient.GetAsync(uri);
//the content needs to update the record in the SwipeDetails table to say that it has been saved.
var content = await response.Content.ReadAsStringAsync();
}
return null;
}
这是它试图联系的方法。如你所见,该方法还以JSON格式返回一些数据除了POST,它还返回一些数据我需要能够处理这些数据:
[HttpPost]
public JsonResult SaveSwipeToServer(int locationId, int userId, int ebCounter, long dateTimeTicks, int swipeDirection, int serverTime)
{
bool result = false;
string errMsg = String.Empty;
int livePunchId = 0;
int backupPunchId = 0;
IClockPunch punch = null;
try
{
punch = new ClockPunch()
{
LocationID = locationId,
Swiper_UserId = userId,
UserID = ebCounter,
ClockInDateTime = DateTimeJavaScript.ConvertJavascriptDateTime(dateTimeTicks),
ClockedIn = swipeDirection.Equals(1),
};
using (IDataAccessLayer dal = DataFactory.GetFactory())
{
DataAccessResult dalResult = dal.CreatePunchForNFCAPI(punch, out livePunchId, out backupPunchId);
if (!dalResult.Result.Equals(Result.Success))
{
throw dalResult.Exception;
}
}
result = true;
}
catch (Exception ex)
{
errMsg = "Something Appeared to go wrong when saving punch information to the horizon database.'r" + ex.Message;
}
return Json(new
{
result = result,
punchDetails = punch,
LivePunchId = livePunchId,
BackUpPunchId = backupPunchId,
timeTicks = DateTimeJavaScript.ToJavaScriptMilliseconds(DateTime.UtcNow),
errorMessage = errMsg
}
,JsonRequestBehavior.AllowGet);
}
目前存储在'content'中的数据只是一条错误消息。
可以在请求正文中发布参数。
public static async Task<SwipeDetails> SaveSwipesToCloud() {
//get unuploaded swips
var swipesnotsved = SwipeRepository.GetUnUploadedSwipes();
var client = new HttpClient() {
BaseAddress = new Uri(URL)
};
var requestUri = "SaveSwipeToServer";
//send it to the cloud
foreach (var item in swipesnotsved) {
//create the parameteres
var data = new Dictionary<string, string>();
data["locationId"] = item.LocationID;
data["userId"] = item.AppUserID;
data["ebCounter"] = item.SwipeID;
data["dateTimeTicks"] = item.DateTimeTicks;
data["swipeDirection"] = item.SwipeDirection;
data["serverTime"] = item.IsServerTime;
var body = new System.Net.Http.FormUrlEncodedContent(data);
var response = await client.PostAsync(requestUri, body);
//the content needs to update the record in the SwipeDetails table to say that it has been saved.
var content = await response.Content.ReadAsStringAsync();
}
return null;
}
我不确定您如何托管您的服务,从您的代码中不清楚。我在应用程序HttpClientPostWebService中托管了我的Web API控制器SwipesController。我不建议使用JsonResult。对于移动客户端,我只返回你需要的类。
你有两个选择:
-
使用get而不是post。
-
使用post。
都在
下面控制器:
namespace HttpClientPostWebService.Controllers
{
public class SwipesController : ApiController
{
[System.Web.Http.HttpGet]
public IHttpActionResult SaveSwipeToServer(int locationId, int userId, int ebCounter, long dateTimeTicks, int swipeDirection, int serverTime)
{
return Ok(new SwipeResponse
{
TestInt = 3,
TestString = "Testing..."
});
}
[System.Web.Http.HttpPost]
public IHttpActionResult PostSwipeToServer([FromBody] SwipeRequest req)
{
return Ok(new SwipeResponse
{
TestInt = 3,
TestString = "Testing..."
});
}
}
public class SwipeRequest
{
public string TestStringRequest { get; set; }
public int TestIntRequest { get; set; }
}
public class SwipeResponse
{
public string TestString { get; set; }
public int TestInt { get; set; }
}
}
客户: async private void Btn_Clicked(object sender, System.EventArgs e)
{
HttpClient client = new HttpClient();
try
{
var result = await client.GetAsync(@"http://uri/HttpClientPostWebService/Api/Swipes?locationId=1&userId=2&ebCounter=3&dateTimeTicks=4&swipeDirection=5&serverTime=6");
var content = await result.Content.ReadAsStringAsync();
var resp = JsonConvert.DeserializeObject<SwipeResponse>(content);
}
catch (Exception ex)
{
}
try
{
var result1 = await client.PostAsync(@"http://uri/HttpClientPostWebService/Api/Swipes",
new StringContent(JsonConvert.SerializeObject(new SwipeRequest() { TestIntRequest = 5, TestStringRequest = "request" }), Encoding.UTF8, "application/json"));
var content1 = await result1.Content.ReadAsStringAsync();
var resp1 = JsonConvert.DeserializeObject<SwipeResponse>(content1);
}
catch (Exception ex)
{
}
}