Xamarin只言片语2——Xamarin下的web api操作
在很多时候,我们是希望手机app是要和服务端关联,并获取服务端的数据的,本篇博文我们看一下在xmarin下,怎么和用web api的方式与服务端连接并获取数据。
首先看web api的开发,本实例是用Visual Studio 2013 with update 4开发
然后创建一个实体类City
publicclassCity
{
publicintCode
{get;set;}
publicstringName
{get;set;}
}
再创建一个WebApiController
[RoutePrefix("api")]
publicclassTestController:ApiController
{
[HttpGet]
[Route("citys")]//通过路由设计为citys
publicIHttpActionResultGetCitys()
{
varcitys=newList<City>(){
newCity(){Code=1,Name="北京"},
newCity(){Code=2,Name="天津"}
};
returnJson(citys);//通过Json方式返回数据
}
[HttpPost]//设定请求方式为get请求
[Route("login")]//通过路由设计为citys
publicIHttpActionResultSaveUser(stringUserName,stringPassword)
{
if(UserName=="aaa"&&Password=="bbb")
{
returnOk(1);
}
else
{
returnOk(0);
}
}
}
并键一点是要把webapi项目布署到IIS上,本例访问地址是:http://192.168.1.106/api
Android端
创建一个Android的空项目。
右击项目,“管理Nuget程序包”,查Restsharp for Android,并安装
新建一个窗体,axml如下:
<?xmlversion="1.0"encoding="utf-8"?>
<LinearLayoutxmlns: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>
后端代码如下:
usingSystem;
usingAndroid.App;
usingAndroid.Content;
usingAndroid.Runtime;
usingAndroid.Views;
usingAndroid.Widget;
usingAndroid.OS;
usingRestSharp;
usingSystem.Net;
usingSystem.Collections.Generic;
namespaceWebApiAndroid
{
[Activity(Label="WebApiAndroid",MainLauncher=true,Icon="@drawable/icon")]
publicclassMainActivity:Activity
{
protectedoverridevoidOnCreate(Bundlebundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Buttonbut1=FindViewById<Button>(Resource.Id.But1);
Buttonbut2=FindViewById<Button>(Resource.Id.But2);
EditTextusername_et=FindViewById<EditText>(Resource.Id.username);
EditTextpassword_et=FindViewById<EditText>(Resource.Id.password);
but1.Click+=delegate
{
RestClientclient=newRestClient(@"http://192.168.1.106/api/");
RestRequestrequest=newRestRequest(@"citys",Method.GET);
client.ExecuteAsync(request,resp=>
{
if(resp.StatusCode==HttpStatusCode.OK)
{
varv=resp.Content;
varcitys=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
{
RestClientclient=newRestClient(@"http://192.168.1.106/api/");
RestRequestrequest=newRestRequest(@"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)
{
varv=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());
}
});
};
}
}
publicclassCity
{
publicintCode
{get;set;}
publicstringName
{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中的代码如下:
usingSystem;
usingSystem.Drawing;
usingFoundation;
usingUIKit;
usingRestSharp;
usingSystem.Net;
usingSystem.Collections.Generic;
namespaceWebApiIPhone
{
publicpartialclassRootViewController:UIViewController
{
publicRootViewController(IntPtrhandle)
:base(handle)
{
}
publicoverridevoidDidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
}
#regionViewlifecycle
publicoverridevoidViewDidLoad()
{
base.ViewDidLoad();
MyBut1.TouchUpInside+=MyBut1_TouchUpInside;
MyBut2.TouchUpInside+=MyBut2_TouchUpInside;
}
voidMyBut2_TouchUpInside(objectsender,EventArgse)
{
RestClientclient=newRestClient(@"http://192.168.1.106/api/");
RestRequestrequest=newRestRequest(@"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)
{
varv=resp.Content;
if(v=="1")
{
InvokeOnMainThread(delegate
{
varalert=newUIAlertView("提示","登录成功:",newAlertDelegate(),"确定");
alert.Show();
});
}
else
{
InvokeOnMainThread(delegate
{
varalert=newUIAlertView("提示","登录失败:",newAlertDelegate(),"确定");
alert.Show();
});
}
}
else
{
InvokeOnMainThread(delegate
{
varalert=newUIAlertView("提示","登录成功:"+resp.StatusCode.ToString(),newAlertDelegate(),"确定");
alert.Show();
});
}
});
}
voidMyBut1_TouchUpInside(objectsender,EventArgse)
{
RestClientclient=newRestClient(@"http://192.168.1.106/api/");
RestRequestrequest=newRestRequest(@"citys",Method.GET);
client.ExecuteAsync(request,resp=>
{
if(resp.StatusCode==HttpStatusCode.OK)
{
varv=resp.Content;
varcitys=SimpleJson.DeserializeObject<List<City>>(v);
InvokeOnMainThread(delegate
{
varalert=newUIAlertView("提示","获取成功:"+citys.Count,newAlertDelegate(),"确定");
alert.Show();
});
}
else
{
InvokeOnMainThread(delegate
{
varalert=newUIAlertView("提示","获取失败!",newAlertDelegate(),"确定");
alert.Show();
});
}
});
}
publicoverridevoidViewWillAppear(boolanimated)
{
base.ViewWillAppear(animated);
}
publicoverridevoidViewDidAppear(boolanimated)
{
base.ViewDidAppear(animated);
}
publicoverridevoidViewWillDisappear(boolanimated)
{
base.ViewWillDisappear(animated);
}
publicoverridevoidViewDidDisappear(boolanimated)
{
base.ViewDidDisappear(animated);
}
#endregion
publicclassAlertDelegate:UIAlertViewDelegate
{
publicoverridevoidClicked(UIAlertViewalertview,nintbuttonIndex)
{
if(buttonIndex==0)
{
//确定处理代码
}
else
{
//取消处理代码
}
}
}
}
publicclassCity
{
publicintCode
{get;set;}
publicstringName
{get;set;}
}
}
这时你会发现,Android和IOS中的请求RestSharp的代码是一致的。
效果如下:
Demo下载
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。