在很多时候,我们是希望手机app是要和服务端关联,并获取服务端的数据的,本篇博文我们看一下在xmarin下,怎么和用web api的方式与服务端连接并获取数据。
创新互联专注为客户提供全方位的互联网综合服务,包含不限于成都网站设计、网站建设、深泽网络推广、重庆小程序开发、深泽网络营销、深泽企业策划、深泽品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联为所有大学生创业者提供深泽建站搭建服务,24小时服务热线:18982081108,官方网址:www.cdcxhl.com
首先看web api的开发,本实例是用Visual Studio 2013 with update 4开发
然后创建一个实体类City
public class City
{
public int Code
{ get; set; }
public string Name
}
再创建一个WebApiController
[RoutePrefix("api")]
public class TestController : ApiController
[HttpGet]
[Route("citys")]//通过路由设计为citys
public IHttpActionResult GetCitys()
var citys = new List() {
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如下:
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:text="确定"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/But1" />
android:inputType="textMultiLine"
android:id="@+id/username" />
android:id="@+id/password" />
android:id="@+id/But2" />
后端代码如下:
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(Resource.Id.But1); Button but2 = FindViewById(Resource.Id.But2); EditText username_et = FindViewById(Resource.Id.username); EditText password_et = FindViewById(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>(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>(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下载 本文标题:Xamarin只言片语2——Xamarin下的webapi操作 网页链接:http://scfushun.com/article/igsgji.html
Button but2 = FindViewById
EditText username_et = FindViewById(Resource.Id.username);
EditText password_et = FindViewById(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>(v);
RunOnUiThread(() => Toast.MakeText(this, "获取成功!" + citys.Count, ToastLength.Short).Show());
RunOnUiThread(() => Toast.MakeText(this, "获取失败:" + resp.StatusCode.ToString(), ToastLength.Short).Show());
});
but2.Click += delegate
RestRequest request = new RestRequest(@"login", Method.POST);
//输入参数
request.AddParameter("UserName", username_et.Text, ParameterType.QueryString);
request.AddParameter("Password", password_et.Text, ParameterType.QueryString);
//上传结果回调函数
if (v == "1")
RunOnUiThread(() => Toast.MakeText(this, "登录成功", ToastLength.Short).Show());
RunOnUiThread(() => Toast.MakeText(this, "登录失败:" + resp.StatusCode.ToString(), ToastLength.Short).Show());
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.Drawing;
using Foundation;
using UIKit;
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)
request.AddParameter("UserName", UserName_TB.Text, ParameterType.QueryString);
request.AddParameter("Password", Password_TB.Text, ParameterType.QueryString);
InvokeOnMainThread(delegate
var alert = new UIAlertView("提示", "登录成功:", new AlertDelegate(), "确定");
alert.Show();
var alert = new UIAlertView("提示", "登录失败:", new AlertDelegate(), "确定");
var alert = new UIAlertView("提示", "登录成功:" + resp.StatusCode.ToString(), new AlertDelegate(), "确定");
void MyBut1_TouchUpInside(object sender, EventArgs e)
var alert = new UIAlertView("提示", "获取成功:" + citys.Count, new AlertDelegate(), "确定");
var alert = new UIAlertView("提示", "获取失败!", new AlertDelegate(), "确定");
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)
//确定处理代码
//取消处理代码
这时你会发现,Android和IOS中的请求RestSharp的代码是一致的。
效果如下:
Demo下载
在线咨询
拨打电话