• Mono for android 访问Webservice和WebApi以及获取和解析JSON


    先看效果,注意:(1)这里由于我的模拟器不支持中文输入,所以,对于这张效果图,我是直接在代码中写死了我的查询城市,在下面的代码中我是没有把要查询的城市写死的。      

            (2)读者要想成功使用本示例的所有代码的话(就是一成不改,这也太懒了哈!),需要读者自己申请一个key,然后放入我的代码中,下面的代码注释中我也有说道,请认真观看。

            (3)改代码本人亲测可行,有图有真相。

            (4)本文全部原创,热烈欢迎广大网友分享本文,但请标明出处。也欢迎大家和我积极交流相关知识。

    布局如大家所见,很简陋,我就不贴代码了哈。

    活动代码:

    using System;
    using Android.App;
    using Android.Content;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.OS;
    using Org;
    using System.Net;
    using System.IO;
    using System.Text;
    using Newtonsoft.Json;
    using System.Text.RegularExpressions;

    namespace App1
    {
    [Activity(Label = "App1", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
    private TextView tv; //一个标签,用来显示查询成功后的JSON数据
    EditText city; //一个输入框,用来接收要传入的参数,我这里用来传递要查询城市的名字
    string queryCity = ""; //记录输入框的内容
    string Url = "http://apis.haoservice.com/weather";//请求的service地址

    protected override void OnCreate(Bundle bundle)
    {
    base.OnCreate(bundle);

    // 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);
    city = FindViewById<EditText>(Resource.Id.city);
    tv = FindViewById<TextView>(Resource.Id.resultText);
    button.Click +=button_Click;
    }


    void button_Click(object sender, EventArgs e)
    {

    if(string.IsNullOrEmpty(city.Text))
    {
    Toast.MakeText(this,"请输入城市名称!",ToastLength.Long).Show();
    return;
    }
    queryCity = city.Text;
    string Body = "cityname=" +System.Web.HttpUtility.UrlEncode(queryCity) + "&key=";//特别注意,这里需要读者自己去申请一个key然后填入
    byte[] data = Encoding.ASCII.GetBytes(Body); //转换为字节数组
    try
    {
    // Create the web request
    HttpWebRequest request = WebRequest.Create(Url) as HttpWebRequest;
    request.ContentLength = data.Length;

    // Set type to POST
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";

    // Write the parameters
    var stream = request.GetRequestStream();
    stream.Write(data, 0, data.Length);
    stream.Close();

    request.BeginGetResponse(new AsyncCallback(ProcessRestJSONHttpResponse), request);
    }
    catch (WebException we)
    {
    tv.Text = we.Message;
    Android.Util.Log.Error("http request", "Exception: " + we.Message);
    }
    catch (System.Exception sysExc)
    {
    tv.Text = sysExc.Message;
    Android.Util.Log.Error("http request", "Exception: " + sysExc.Message);
    }


    }

    void ProcessRestJSONHttpResponse(IAsyncResult iar)
    {
    try
    {
    HttpWebRequest request = (HttpWebRequest)iar.AsyncState;
    HttpWebResponse response;
    response = (HttpWebResponse)request.EndGetResponse(iar);
    System.IO.StreamReader strm = new System.IO.StreamReader(
    response.GetResponseStream());
    string result = strm.ReadToEnd();
    this.RunOnUiThread(delegate
    {
    tv.Text = result;
    });
    /* 这里提供2种去掉字符串里面空格的方法,JSON数据是不允许里面有特殊字符的否则解析会出错
    **/
    string test1 = result.Replace(" ", ""); //去掉空格
    string test = Regex.Replace(result, @"\s", "");//去掉空格回车等特殊字符 这里test1和test内容是一样的,我只是列举2种不同的方法
    /* 第一种解析JSON方法:反序列化 使用JSON.NET 的索引器访问 官网地址:http://www.newtonsoft.com/json
    相对应的就是序列化:string json = JsonConvert.SerializeObject(team);其中team就是JSON对象
    */
    var results = JsonConvert.DeserializeObject(test1);//反序列化,可以通过索引器来访问,到此就完成了json的解析工作

    //就下来就可以用results的索引方式访问任何你想要的JSON中的数据内容了。

    }
    catch (System.Exception sysExc)
    {
    Android.Util.Log.Error("http response", "Exception: " + sysExc.Message);
    this.RunOnUiThread(() => tv.Text = "Exception: " + sysExc.Message);
    }
    }
    }
    }

  • 相关阅读:
    【二分图匹配入门专题1】L
    【二分图匹配入门专题1】K
    【km算法模板+总结】
    【二分匹配入门专题1】J
    【自定义博客园~~~】
    【二分图匹配入门专题1】I
    【二分图匹配入门专题1】H
    【二分图匹配入门专题1】G
    【二分图匹配入门专题1】E
    【二分图匹配入门专题1】F
  • 原文地址:https://www.cnblogs.com/nightswatch/p/4250973.html
Copyright © 2020-2023  润新知