Xamarin只言片语2――Xamarin下的web api操作

在很多时候,我们是希望手机app是要和服务端关联,并获取服务端的数据的,本篇博文我们看一下在xmarin下,怎么和用web api的方式与服务端连接并获取数据。

首先看web api的开发,本实例是用Visual Studio 2013 with update 4开发


wKiom1UFB66AkX0YAAMS-_7_ELk270.jpg

wKioL1UFCNPgPUd3AAJGLrt5OVM185.jpg


然后创建一个实体类City

public class City

 {

     public int Code

     { getset; }

     public string Name

     { getset; }

 }

再创建一个WebApiController

    [RoutePrefix("api")]

public class TestController : ApiController

{

    [HttpGet]

    [Route("citys")]//通过路由设计为citys

    public IHttpActionResult GetCitys()

    {

        var citys = new List<City>() {

        new City(){ Code=1,Name="北京"},

        new City(){Code=2,Name="天津"}

        };

        return Json(citys);//通过Json方式返回数据

    }

 

    [HttpPost]//设定请求方式为get请求

    [Route("login")]//通过路由设计为citys

    public IHttpActionResult SaveUser(string UserName, string Password)

    {

        if (UserName == "aaa" && Password == "bbb")

        {

            return Ok(1);

        }

        else

        {

            return Ok(0);

        }

    }

}

并键一点是要把webapi项目布署到IIS上,本例访问地址是:http://192.168.1.106/api

Android

创建一个Android的空项目。

wKiom1UFB_WAOpxSAAM3oRHZlwM169.jpg

右击项目,“管理Nuget程序包”,查Restsharp for Android,并安装

wKioL1UFCT_SSdxdAARS1JxKTXo273.jpg

wKiom1UFCE6zxfMnAACUStJmqd8474.jpg

新建一个窗体,axml如下:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent">

    <Button

        android:text="确定"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:id="@+id/But1" />

    <EditText

        android:inputType="textMultiLine"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:id="@+id/username" />

    <EditText

        android:inputType="textMultiLine"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:id="@+id/password" />

    <Button

        android:text="确定"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:id="@+id/But2" />

</LinearLayout>

后端代码如下:

using System;

using Android.App;

using Android.Content;

using Android.Runtime;

using Android.Views;

using Android.Widget;

using Android.OS;

using RestSharp;

using System.Net;

using System.Collections.Generic; 

namespace WebApiAndroid

{

    [Activity(Label = "WebApiAndroid", MainLauncher = true, Icon = "@drawable/icon")]

    public class MainActivity : Activity

    {

        protected override void OnCreate(Bundle bundle)

        {

            base.OnCreate(bundle); 

            SetContentView(Resource.Layout.Main); 

            Button but1 = FindViewById<Button>(Resource.Id.But1);

            Button but2 = FindViewById<Button>(Resource.Id.But2);

            EditText username_et = FindViewById<EditText>(Resource.Id.username);

            EditText password_et = FindViewById<EditText>(Resource.Id.password);

            but1.Click += delegate

            {

                RestClient client = new RestClient(@"http://192.168.1.106/api/");

                RestRequest request = new RestRequest(@"citys"Method.GET);

                client.ExecuteAsync(request, resp =>

                {

                    if (resp.StatusCode == HttpStatusCode.OK)

                    {

                        var v = resp.Content;

                        var citys = SimpleJson.DeserializeObject<List<City>>(v);

                        RunOnUiThread(() => Toast.MakeText(this"获取成功!" + citys.Count, ToastLength.Short).Show());

                    }

                    else

                    {

                        RunOnUiThread(() => Toast.MakeText(this"获取失败:" + resp.StatusCode.ToString(), ToastLength.Short).Show());

                    }

                }); 

            }; 

            but2.Click += delegate

            {

                RestClient client = new RestClient(@"http://192.168.1.106/api/");

                RestRequest request = new RestRequest(@"login"Method.POST);

                //输入参数

                request.AddParameter("UserName", username_et.Text, ParameterType.QueryString);

                request.AddParameter("Password", password_et.Text, ParameterType.QueryString);

                //上传结果回调函数

                client.ExecuteAsync(request, resp =>

                {

                    if (resp.StatusCode == HttpStatusCode.OK)

                    {

                        var v = resp.Content;

                        if (v == "1")

                        {

                            RunOnUiThread(() => Toast.MakeText(this"登录成功"ToastLength.Short).Show());

                        }

                        else

                        {

                            RunOnUiThread(() => Toast.MakeText(this"登录失败:" + resp.StatusCode.ToString(), ToastLength.Short).Show());

                        }

                    }

                    else

                    {

                        RunOnUiThread(() => Toast.MakeText(this"获取失败:" + resp.StatusCode.ToString(), ToastLength.Short).Show());

                    }

                }); 

            };

        }

    } 

    public class City

    {

        public int Code

        { getset; } 

        public string Name

        { getset; } 

    }

}

wKiom1UFCL6AvGeTAAHo2Wf5aMc476.jpg

wKioL1UFCeOwuV4AAAH6ZJlU_2g591.jpg

IPhone

对于IOS开发,也是同样的,在Visual Studio中新建一个IPhone的应用。

wKiom1UFCRWSZ9BhAANacAkFI70549.jpg

这时要求连接一Mac作为Build Host

wKiom1UFCVXi45JtAAH9p4oQ3ks814.jpg

这里我设置的是我的mac系统

wKioL1UFCrDBnt4AAAG1wJYqMlg784.jpg

同时打开Mac上的xamarin.ios build host,开始配对

wKioL1UFCujzXqRvAAI-WNEkCnA316.jpg

在开发端输入mac端生成的pin

wKioL1UFCxXRWZpXAAE3ZdGK35g313.jpg

开始配对,这里要注意你的visual studio所在的windows要与 build host所在的mac处于同一个局域网内。

 

右键IOS项目,打开nuget,安装Restsharp for ios

wKioL1UFCzfxO02lAASkY9w7eFc413.jpg

还有另一个办法来添加RestSharp引用,打开下面网址

https://github.com/restsharp/RestSharp

下载程序包

wKiom1UFCkaBkGVsAAQhSMaoSYY452.jpg

重新编译RestSharp.IOS,并把bin目录中生成(最好是Release)RestSharp.IOS.dll引用到当前的IOS项目中。

打开IOS项目中的MainStoryboard.storyboard,添加两个按钮MyBut1MyBut2,和两个文本框,分别是UserName_TBPassword_TB

wKiom1UFCnmSn_u0AABoEHySc-g670.jpg

后台Controller中的代码如下:

using System;

using System.Drawing; 

using Foundation;

using UIKit;

using RestSharp;

using System.Net;

using System.Collections.Generic; 

namespace WebApiIPhone

{

    public partial class RootViewController : UIViewController

    {

        public RootViewController(IntPtr handle)

            : base(handle)

        {

        } 

        public override void DidReceiveMemoryWarning()

        {

            base.DidReceiveMemoryWarning();

        } 

        #region View lifecycle 

        public override void ViewDidLoad()

        {

            base.ViewDidLoad(); 

            MyBut1.TouchUpInside += MyBut1_TouchUpInside;

            MyBut2.TouchUpInside += MyBut2_TouchUpInside;

        }

 

        void MyBut2_TouchUpInside(object sender, EventArgs e)

        {

            RestClient client = new RestClient(@"http://192.168.1.106/api/");

            RestRequest request = new RestRequest(@"login"Method.POST);

            //输入参数

            request.AddParameter("UserName", UserName_TB.Text, ParameterType.QueryString);

            request.AddParameter("Password", Password_TB.Text, ParameterType.QueryString);

            //上传结果回调函数

            client.ExecuteAsync(request, resp =>

            {

                if (resp.StatusCode == HttpStatusCode.OK)

                {

                    var v = resp.Content;

                    if (v == "1")

                    {

                        InvokeOnMainThread(delegate

                            {

                                var alert = new UIAlertView("提示""登录成功:"new AlertDelegate(), "确定");

                                alert.Show();

                            });

                    }

                    else

                    {

                        InvokeOnMainThread(delegate

                            {

                                var alert = new UIAlertView("提示""登录失败:"new AlertDelegate(), "确定");

                                alert.Show();

                            });

                    }

                }

                else

                {

                    InvokeOnMainThread(delegate

                   {

                       var alert = new UIAlertView("提示""登录成功:" + resp.StatusCode.ToString(), new AlertDelegate(), "确定");

                       alert.Show();

                   }); 

                }

            });

        } 

        void MyBut1_TouchUpInside(object sender, EventArgs e)

        {

            RestClient client = new RestClient(@"http://192.168.1.106/api/");

            RestRequest request = new RestRequest(@"citys"Method.GET);

            client.ExecuteAsync(request, resp =>

            {

                if (resp.StatusCode == HttpStatusCode.OK)

                {

                    var v = resp.Content;

                    var citys = SimpleJson.DeserializeObject<List<City>>(v);

 

                    InvokeOnMainThread(delegate

                    {

                        var alert = new UIAlertView("提示""获取成功:" + citys.Count, new AlertDelegate(), "确定");

                        alert.Show();

                    }); 

                }

                else

                {

                    InvokeOnMainThread(delegate

                    {

                        var alert = new UIAlertView("提示""获取失败!"new AlertDelegate(), "确定");

                        alert.Show();

                    });

                }

            }); 

        } 

        public override void ViewWillAppear(bool animated)

        {

            base.ViewWillAppear(animated);

        } 

        public override void ViewDidAppear(bool animated)

        {

            base.ViewDidAppear(animated);

        } 

        public override void ViewWillDisappear(bool animated)

        {

            base.ViewWillDisappear(animated);

        } 

        public override void ViewDidDisappear(bool animated)

        {

            base.ViewDidDisappear(animated);

        } 

        #endregion 

        public class AlertDelegate : UIAlertViewDelegate

        {

            public override void Clicked(UIAlertView alertview, nint buttonIndex)

            {

                if (buttonIndex == 0)

                {

                    //确定处理代码

                }

                else

                {

                    //取消处理代码

                }

            }

        } 

    } 

    public class City

    {

        public int Code

        { getset; }

        public string Name

        { getset; } 

    }

}

这时你会发现,AndroidIOS中的请求RestSharp的代码是一致的。

效果如下:

wKiom1UFCu7SwIaAAAEmsaBXUiI156.jpg

wKioL1UFDBPhmF0eAAElFt8MYqU546.jpg

wKiom1UFCu-QEA6HAAElcruJ_JQ663.jpg

Demo下载

你可能感兴趣的:(webapi,Xamarin,RestSharp)