简体   繁体   English

如何从C#Xamarin中的HTTP发布中获取数据?

[英]How can I get data from a HTTP post in C# Xamarin?

I am trying to POST some data using HTTPClient. 我正在尝试使用HTTPClient发布一些数据。 I have managed to use the following code when simply getting data in JSON format, but it doesn't seem to work for a POST. 当仅以JSON格式获取数据时,我设法使用了以下代码,但对于POST似乎无效。

This is the code I'm using: 这是我正在使用的代码:

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;
}

This is the method it's trying to contact. 这是它尝试联系的方法。 As you can see, the method also returns some data in JSON format so as well as a POST it's also getting some data back which I need to be able to work with: 如您所见,该方法还以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);
}

At the moment the data being stored in 'content' is just an error message. 目前,存储在“内容”中的数据只是一条错误消息。

I am not sure how you host your service, it is not clear from your code. 我不确定您如何托管服务,但您的代码尚不清楚。 I hosted mine in Web API controller SwipesController in application HttpClientPostWebService. 我将Web控制器SwipesController托管在应用程序HttpClientPostWebService中。 I don't suggest to use JsonResult. 我不建议使用JsonResult。 For mobile client I would just return the class you need. 对于移动客户端,我只返回您需要的课程。

You have 2 options: 您有2个选择:

  1. Use get not post. 使用获取不发布。

  2. Use post. 使用帖子。

Both cases are below 两种情况都在下面

Controller: 控制器:

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; }
    }
}

Client: 客户:

    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)
        {
        }
    }

You can post the parameters in the body of the request. 您可以将参数发布在请求的正文中。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM