您好,登錄后才能下訂單哦!
在很多時(shí)候,我們是希望手機(jī)app是要和服務(wù)端關(guān)聯(lián),并獲取服務(wù)端的數(shù)據(jù)的,本篇博文我們看一下在xmarin下,怎么和用web api的方式與服務(wù)端連接并獲取數(shù)據(jù)。
首先看web api的開(kāi)發(fā),本實(shí)例是用Visual Studio 2013 with update 4開(kāi)發(fā)
然后創(chuàng)建一個(gè)實(shí)體類City
public class City
{
public int Code
{ get; set; }
public string Name
{ get; set; }
}
再創(chuàng)建一個(gè)WebApiController
[RoutePrefix("api")]
public class TestController : ApiController
{
[HttpGet]
[Route("citys")]//通過(guò)路由設(shè)計(jì)為citys
public IHttpActionResult GetCitys()
{
var citys = new List<City>() {
new City(){ Code=1,Name="北京"},
new City(){Code=2,Name="天津"}
};
return Json(citys);//通過(guò)Json方式返回?cái)?shù)據(jù)
}
[HttpPost]//設(shè)定請(qǐng)求方式為get請(qǐng)求
[Route("login")]//通過(guò)路由設(shè)計(jì)為citys
public IHttpActionResult SaveUser(string UserName, string Password)
{
if (UserName == "aaa" && Password == "bbb")
{
return Ok(1);
}
else
{
return Ok(0);
}
}
}
并鍵一點(diǎn)是要把webapi項(xiàng)目布署到IIS上,本例訪問(wèn)地址是:http://192.168.1.106/api
Android端
創(chuàng)建一個(gè)Android的空項(xiàng)目。
右擊項(xiàng)目,“管理Nuget程序包”,查Restsharp for Android,并安裝
新建一個(gè)窗體,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, "獲取失?。?/span>" + 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);
//輸入?yún)?shù)
request.AddParameter("UserName", username_et.Text, ParameterType.QueryString);
request.AddParameter("Password", password_et.Text, ParameterType.QueryString);
//上傳結(jié)果回調(diào)函數(shù)
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, "登錄失?。?/span>" + resp.StatusCode.ToString(), ToastLength.Short).Show());
}
}
else
{
RunOnUiThread(() => Toast.MakeText(this, "獲取失?。?/span>" + resp.StatusCode.ToString(), ToastLength.Short).Show());
}
});
};
}
}
public class City
{
public int Code
{ get; set; }
public string Name
{ get; set; }
}
}
IPhone端
對(duì)于IOS開(kāi)發(fā),也是同樣的,在Visual Studio中新建一個(gè)IPhone的應(yīng)用。
這時(shí)要求連接一Mac作為Build Host
這里我設(shè)置的是我的mac系統(tǒng)
同時(shí)打開(kāi)Mac上的xamarin.ios build host,開(kāi)始配對(duì)
在開(kāi)發(fā)端輸入mac端生成的pin碼
開(kāi)始配對(duì),這里要注意你的visual studio所在的windows要與 build host所在的mac處于同一個(gè)局域網(wǎng)內(nèi)。
右鍵IOS項(xiàng)目,打開(kāi)nuget,安裝Restsharp for ios
還有另一個(gè)辦法來(lái)添加RestSharp引用,打開(kāi)下面網(wǎng)址
https://github.com/restsharp/RestSharp
下載程序包
重新編譯RestSharp.IOS,并把bin目錄中生成(最好是Release下)的RestSharp.IOS.dll引用到當(dāng)前的IOS項(xiàng)目中。
打開(kāi)IOS項(xiàng)目中的MainStoryboard.storyboard,添加兩個(gè)按鈕MyBut1和MyBut2,和兩個(gè)文本框,分別是UserName_TB和Password_TB
后臺(tái)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);
//輸入?yún)?shù)
request.AddParameter("UserName", UserName_TB.Text, ParameterType.QueryString);
request.AddParameter("Password", Password_TB.Text, ParameterType.QueryString);
//上傳結(jié)果回調(diào)函數(shù)
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
{ get; set; }
public string Name
{ get; set; }
}
}
這時(shí)你會(huì)發(fā)現(xiàn),Android和IOS中的請(qǐng)求RestSharp的代碼是一致的。
效果如下:
Demo下載
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。