如何在Xamarin.Forms中接收来自服务器的响应 [英] How to receive response from server in Xamarin.Forms

查看:170
本文介绍了如何在Xamarin.Forms中接收来自服务器的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个HTTP客户端,该客户端将数据发送到我的服务器.此数据将查询我的服务器,该服务器将返回JSON对象.如何从服务器接收JSON对象响应并将其插入数据库?

I have created an HTTP Client that sends data to my server. This data will query my server that will return a JSON object. How can I receive the JSON Object response from my server and insert it into my database?

下面的代码将向服务器发送 ContactID ,服务器将返回JSON对象如何从服务器获取JSON对象?我将在代码中添加什么?我已添加

The code below will send a ContactID to my server and my server will return a JSON Object How can I get the JSON Object from my server? What will I add to my code? I have added

var data = await response.Content.ReadAsStringAsync();

但我不知道如何进行.

try
        {
            var db = DependencyService.Get<ISQLiteDB>();
            var conn = db.GetConnection();

            var sql = "SELECT * FROM tblUser WHERE ContactID = '" + contact + "'";
            var getUser = conn.QueryAsync<UserTable>(sql);
            var resultCount = getUser.Result.Count;

            //Check if the user has been sync
            if (resultCount < 1)
            {
                try
                {
                    syncStatus.Text = "Syncing user to server...";

                    var link = Constants.requestUrl + "Host=" + host + "&Database=" + database + "&Contact=" + contact + "&Request=8qApc8";
                    string contentType = "application/json";
                    JObject json = new JObject
                    {
                        { "ContactID", contact }
                    };

                    HttpClient client = new HttpClient();
                    var response = await client.PostAsync(link, new StringContent(json.ToString(), Encoding.UTF8, contentType));
                    var data = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        var content = await response.Content.ReadAsStringAsync();
                        var userresult = JsonConvert.DeserializeObject<IList<UserData>>(content);
                        var count = userresult.Count;

                        for (int i = 0; i < count; i++)
                        {
                            try
                            {
                                syncStatus.Text = "Syncing user to server...";

                                var item = userresult[i];
                                var contactID = item.ContactID;
                                var userID = item.UserID;
                                var userPassword = item.UserPassword;
                                var userType = item.UserType;
                                var userStatus = item.UserStatus;
                                var lastSync = item.LastSync;
                                var serverUpdate = item.ServerUpdate;
                                var mobileUpdate = item.MobileUpdate;

                                var user = new UserTable
                                {
                                    ContactID = Convert.ToInt32(contactID),
                                    UserID = userID,
                                    UserPassword = userPassword,
                                    UserType = userType,
                                    UserStatus = userStatus,
                                    LastSync = lastSync,
                                    ServerUpdate = serverUpdate,
                                    MobileUpdate = mobileUpdate
                                };

                                await conn.InsertAsync(user);
                            }
                            catch (Exception ex)
                            {
                                Console.Write("Syncing user error " + ex.Message);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.Write("Syncing User Error " + ex.Message);
                }
            }

我的PHP代码将使用从 Xamarin HTTP Client 收到的 ContactID 查询我的数据库.

My PHP code will query my database with the ContactID received from Xamarin HTTP Client.

$json_str = file_get_contents('php://input');
    $json_obj = json_decode($json_str);

    $ContactID = $json_obj->ContactID;

    $sql = "SELECT * FROM tblUser WHERE ContactID = '$ContactID'";
    $result = mysqli_query($conn, $sql);
    $count = mysqli_num_rows($result);

    if($count > 0){
        while ($row = @mysqli_fetch_array($result)) {
            $decr = CryptRC4(FromHexDump($row['UserPassword']), $key);

            $ar[] = array(
                'ContactID' => $row['ContactID'],
                'UserID' => $row['UserID'],
                'UserPassword' => $decr,
                'UserType' => $row['UserType'],
                'UserStatus' => $row['UserStatus'],
                'LastSync' => $sync,
                'ServerUpdate' => $row['ServerUpdate'],
                'MobileUpdate' => $row['MobileUpdate']
            );

            print json_encode($ar);

            //Update LastSync DateTime
            $sql = "UPDATE tblUser SET LastSync = '$sync' WHERE ContactID = '$ContactID'";
            mysqli_query($conn, $sql);
        }
    }    

推荐答案

上面示例中的最后一条语句以字符串格式给出了json对象的列表.

Last statement in your example above gives list of json objects in string format.

var data = await response.Content.ReadAsStringAsync();

您需要将其转换回对象列表.为了让您的项目了解对象的定义,请创建一个具有公共属性的普通类(如下所示)

You need to convert that back to list of objects. To let your project know about definition of the object, create a plain class with public properties (Something like below)

public class UserLog
{
    public int ContactId { get; set; }
    public string Log { get; set; }
    public DateTime LogDate { get; set; }
}

Newtonsoft.Json (由James Newton-King设计)添加到项目中的Nuget包中,以便可以使用json.

Add Newtonsoft.Json (by James Newton-King) Nuget package to your project so that you can work with json.

要将变量"data"的内容转换为UserLog对象的列表,请编写类似

To convert content of the variable 'data' into list of UserLog objects, write code like

var list = NewtonsoftUtil<IList<UserLog>>.DeserializeObject(data);

(在文件顶部添加using Newtonsoft.Json;)

请告诉我这是否有帮助.

Please let me know if this helps.

这篇关于如何在Xamarin.Forms中接收来自服务器的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆