您好,登錄后才能下訂單哦!
在很多時候,我們是希望手機app是要和服務端關聯,并獲取服務端的數據的,本篇博文我們看一下在xmarin下,怎么和用web api的方式與服務端連接并獲取數據。
首先看web api的開發,本實例是用Visual Studio 2013 with update 4開發
然后創建一個實體類City
public class City
{
public int Code
{ get; set; }
public string Name
{ get; set; }
}
再創建一個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的空項目。
右擊項目,“管理Nuget程序包”,查Restsharp for Android,并安裝
新建一個窗體,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
{ get; set; }
public string Name
{ get; set; }
}
}
IPhone端
對于IOS開發,也是同樣的,在Visual Studio中新建一個IPhone的應用。
這時要求連接一Mac作為Build Host
這里我設置的是我的mac系統
同時打開Mac上的xamarin.ios build host,開始配對
在開發端輸入mac端生成的pin碼
開始配對,這里要注意你的visual studio所在的windows要與 build host所在的mac處于同一個局域網內。
右鍵IOS項目,打開nuget,安裝Restsharp for ios
還有另一個辦法來添加RestSharp引用,打開下面網址
https://github.com/restsharp/RestSharp
下載程序包
重新編譯RestSharp.IOS,并把bin目錄中生成(最好是Release下)的RestSharp.IOS.dll引用到當前的IOS項目中。
打開IOS項目中的MainStoryboard.storyboard,添加兩個按鈕MyBut1和MyBut2,和兩個文本框,分別是UserName_TB和Password_TB
后臺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
{ get; set; }
public string Name
{ get; set; }
}
}
這時你會發現,Android和IOS中的請求RestSharp的代碼是一致的。
效果如下:
Demo下載
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。