【问题标题】:How can I get data from a HTTP post in C# Xamarin?如何从 C# Xamarin 中的 HTTP 帖子获取数据?
【发布时间】:2016-11-07 14:42:20
【问题描述】:

我正在尝试使用 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);
}

目前存储在“内容”中的数据只是一条错误消息。

【问题讨论】:

  • 如果您通过查询字符串传递所有数据,您可以将您的操作方法定义为 HttpGet 操作。您的请求没有发回任何数据。
  • 你有例子吗?请求最后返回 Json 数据。
  • 如果您提供我可以调用 SaveSwipesToCloud 的 URI,我可以给您示例。我需要 URI 来测试我为你编写的代码
  • 如果你想 POST,简单的答案是使用PostAsync(),而不是GetAsync(),这自然是一个GET。
  • @SamiKuhmonen 是的,但他需要发布数据而不仅仅是调用 Post,这就是我想在提供解决方案之前测试的内容

标签: c# visual-studio xamarin http-post xamarin.forms


【解决方案1】:

您可以在请求正文中发布参数。

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

【讨论】:

  • 您好,感谢您的回答。我试过了,但仍然收到错误 500。
  • 通过一些调整就可以了。
  • @connersz,做了哪些调整。是答案中提供的代码吗?如果是这样,请告诉我,以便我可以更新答案以使其相关。
  • 嗯,唯一需要的是参数中的整数需要转换为字符串。
  • 好的,我明白了。因为我不知道示例中的这些属性类型是什么,所以我没有意识到这一点。所以我想那时真的不需要更新答案
【解决方案2】:

我不确定您是如何托管服务的,您的代码中并不清楚。我在应用程序 HttpClientPostWebService 中的 Web API 控制器 SwipesController 中托管了我的。我不建议使用 JsonResult。对于移动客户端,我只会返回您需要的课程。

你有两个选择:

  1. 使用获取不发布。

  2. 使用帖子。

以下两种情况

控制器:

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

【讨论】:

  • 参数呢?我目前遇到的问题是控制器正在返回默认错误页面,这导致我认为参数没有正确传递。
  • @connersz 我曾多次要求您提供 URI,我可以在其中测试您的服务和/或示例项目,以便查看您的服务定义并测试客户端代码
  • 无法访问此站点 dev2.core.thinking-software.com 的服务器 DNS 地址无法找到。我还需要知道您如何托管它。是web api、svc等吗?
  • 我可以在内部和外部访问该页面。错误消息是错误 400,错误请求。我不太了解它是如何托管的,但它只是在 IIS 上运行,它只是控制器中的一个方法,可以使用链接访问。
  • 这是我最后一次要求你提供我可以测试的 URI,之后我放弃了。
猜你喜欢
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 2016-10-04
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
相关资源
最近更新 更多