原文:大叔也说Xamarin~Android篇~调用远程API接口,发POST请求
Xamarin我们在上节已经教大家如何去部署它的环境了,今天来说一个实际的例子,使用android客户调用.net web api的一个接口,并发送POST请求,当服务端回到请求后做出响应,客户端android将响应的内容输出,并跳换到别一个Activity页面,在新视图上加载网页内容到webView控件上,整个流程结束!
一 在主页面上添加几个表单元素,账号,密码,登陆按钮,并在Activity类的OnCreate方法中为它们赋值,并添加按钮的click事件
protected override void OnCreate (Bundle savedInstanceState) { base.OnCreate (savedInstanceState); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button> (Resource.Id.myButton); button.Click += delegate { button.Text = string.Format ("{0} clicks!", count++); }; Android.Util.Log.Info ("normal", "日志zzl"); var loginBtn = FindViewById<Button> (Resource.Id.loginBtn); var username = FindViewById<TextView> (Resource.Id.username); var password = FindViewById<TextView> (Resource.Id.password); var result = FindViewById<TextView> (Resource.Id.result); loginBtn.Click += delegate { string url = "http://api.xuexiba.com/v1/User/Login"; //创建HttpClient(注意传入HttpClientHandler) using (var http = new HttpClient ()) { var content = new FormUrlEncodedContent (new Dictionary<string, string> () { { "username",username.Text }, { "password",password.Text } }); var response = http.PostAsync (url, content); result.Text = response.Result.Content.ReadAsStringAsync ().Result; Intent intent = new Intent(this, typeof(ViewPageActivity)); StartActivity(intent); } }; }
二 在ViewPageActivity里添加一个webView用来显示网页的内容,如下代码
protected override void OnCreate (Bundle savedInstanceState) { base.OnCreate (savedInstanceState); SetContentView (Resource.Layout.ViewPage); var webView = FindViewById<WebView> (Resource.Id.webView); //启用Javascript Enable webView.Settings.JavaScriptEnabled = true; //载入网址 webView.LoadUrl ("http://www.sina.com"); //直接在当前webView上打开 webView.SetWebViewClient (new CustWebViewClient ()); }
注意,代码webView.SetWebViewClient (new CustWebViewClient ())表示使用现有的webView加载网页内容,而如果不加这行,那么网页将使用系统自带的浏览器进行加载,
下载看一下CustWebViewClient 这个类的内容
public class CustWebViewClient : WebViewClient { public override bool ShouldOverrideUrlLoading (WebView view, string url) { view.LoadUrl (url); return true; } }
OK,在我们设计页面时,可以直接从工具箱上进行拖动,最后布局向这样
最后进行APK的生成,我们的程序包就算完成了!
时间: 2024-11-03 18:49:59