Xamarin只言片语2——Xamarin下的web api操作
在很多时候,我们是希望手机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下载
本文转自桂素伟51CTO博客,原文链接: http://blog.51cto.com/axzxs/1620497,如需转载请自行联系原作者
Xamarin只言片语2——Xamarin下的web api操作相关推荐
- Xamarin只言片语1——Xamarin下的弹框
有一段时间没有写博客了,一是因为身体原因,二是因为需要充充电.过去的一段时间,做了一些xamarin的开发,有一些小的心得,就想着把用过的一些知识点共享出来,给大家分享,让学习xamrin的人少走一些 ...
- Windows下使用Java API操作HDFS的常用方法
场景 Windows下配置Hadoop的Java开发环境以及用Java API操作HDFS: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/det ...
- Xamarin只言片语3——Xamarin.Android下支付宝(Alipay SDK)使用
开发环境Visual Studio 2015,Xamarin 3.11.1537,Xamarin Android5.1.7.12 下载支付宝移动支付的SDK(http://doc.open.alipa ...
- Xamarin只言片语4——Xamarin.Android百度地图绑定
先下载百度地图http://lbsyun.baidu.com/sdk/download?selected=mapsdk_basicmap,mapsdk_searchfunction,mapsdk_lb ...
- Xamarin只言片语系列
把自己写xamarin中的一些知识点记录下来,分享给大家,欢迎指正. Xamarin只言片语1--Xamarin下的弹框 Xamarin只言片语2--Xamarin下的web api操作 更新中--
- Dynamics CRM2016 Web API之创建记录
前篇介绍了通过primary key来查询记录,那query的知识点里面还有很多需要学习的,这个有待后面挖掘,本篇来简单介绍下用web api的创建记录. 直接上代码,这里的entity的属性我列了几 ...
- 详解VS2012发布web api流程
VS2012虽然已经十分久远了,但是仍然有一些系统是使用2012开发的. 使用Visual Studio发布系统是一件非常轻松的事情,尤其是使用VS2017,都是一键发布.不过在VS2012下发布we ...
- 1.1ASP.NET Web API 2入门
HTTP 不只是为了生成 web 页面.它也是建立公开服务和数据的 Api 的强大平台.HTTP 是简单的. 灵活的和无处不在.你能想到的几乎任何平台有 HTTP 库,因此,HTTP 服务可以达到范围 ...
- ASP.NET Web API 应用教程(一) ——数据流使用
相信已经有很多文章来介绍ASP.Net Web API 技术,本系列文章主要介绍如何使用数据流,HTTPS,以及可扩展的Web API 方面的技术,系列文章主要有三篇内容. 主要内容如下: I 数据 ...
最新文章
- html的分类与特点
- HTTP Status 500 - Servlet.init() for servlet springmvc threw exception
- 在继承类中,父类在子类中初始化问题,已解决
- sencha touch 模仿tabpanel导航栏TabBar(2013-11-7)
- 我是如何学习写一个操作系统(一):开篇
- 牛客小白月赛12:月月给华华出题(欧拉函数)
- 团队项目改进与详细设计
- JavaScript的学习--生成二维码
- 定时关机win10_长按电源键强制关机,真的会弄坏电脑吗?
- Ubuntu Linux 下 Ffmpeg 及 Mencoder 安装使用小结
- python第三方库官方文档汇总
- matlab 线型、标记、颜色
- ArcGis中计算栅格数据指定区域的面积
- linux qt qpa linuxfb,Linux qt qt.qpa.plugin: Could not load the Qt platform plugin xcb error解决方...
- 125KHz 100cm ID 读卡电路_NX系列PLC-NX-ID数字输入单元_欧姆龙继电器_欧姆龙PLC_欧姆龙接近开关...
- 2021-2027全球与中国成像雷达市场现状及未来发展趋势
- 华为电脑和手机一碰传_华为手机怎么一碰传连接电脑传输照片和文件
- 什么是脚本语言(python脚本是什么?)
- 电商运营中京东运营法则
- 如何租用虚拟服务器,怎么租用虚拟主机