繁体   English   中英

从 xamarin android 应用程序中的网络服务器访问 API

[英]Accessing an API from webserver in xamarin android application

将 API 的结果解析到我的 textview 对象时遇到问题...拜托,我需要帮助:

{"items":[{"id":0,"shortname":"NETD","_links":{"self":{"href":"http://api.iolab.net/v1/exams/0"}}}]

这是我的代码:

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
    //EditText latitude = FindViewById<EditText>(Resource.Id.editText1);
    EditText latitude = FindViewById<EditText>(Resource.Id.editText1);
    Button button = FindViewById<Button>(Resource.Id.button1);
    button.Click += async (sender, e) =>
    {
        string url = "http://api.iolab.net/v1/exams?";

        // Fetch the information asynchronously, parse the results,
        // then update the screen:
        JsonValue json = await FetchExamAsync(url);
        ParseAndDisplay(json);
    };

}

private async Task<JsonValue> FetchExamAsync(string url)
{
    // Create an HTTP web request using the URL:
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
    request.ContentType = "application/json";
    request.Method = "GET";

    // Send the request to the server and wait for the response:
    using (WebResponse response = await request.GetResponseAsync())
    {
        // Get a stream representation of the HTTP web response:
        using (Stream stream = response.GetResponseStream())
        {
            // Use this stream to build a JSON document object:
            JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
            Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());

            // Return the JSON document:
            return jsonDoc;
        }

    } 
}

private void ParseAndDisplay(JsonValue json)
{

    TextView id = FindViewById<TextView>(Resource.Id.textView1);
    TextView Shortname = FindViewById<TextView>(Resource.Id.textView2);
    TextView links = FindViewById<TextView>(Resource.Id.textView3);

    // Extract the array of name/value results for the field name "item":
    // Note that there is no exception handling for when this field is not found.
    JsonValue Results = json["items"];
    id.Text = Results["id"];

    Shortname.Text = Results["shortname"];
    links.Text = Results["_links"];

}

我认为在 .NET 应用程序(包括 Xamarin)中解析 json 的最佳方法是使用Newtonsoft nuget 包和http://json2csharp.com/网站

如果您没有遵循 Xamarin 架构,请将您的异步调用放在可移植库中,因为这可以在所有平台上使用。

这是 newtosoft 的示例:

//generated with json2csharp
//each class correspond to the json string retrieve by the back end

//{"href":"http://api.iolab.net/v1/exams/0"}
public class Self
{
    public string href { get; set; }
}

//"_links":{"self":{"href":"http://api.iolab.net/v1/exams/0"}
public class Links
{
    public Self self { get; set; }
}

//{"items":[{"id":0,"shortname":"NETD","_links":{"self":{"href":"http://api.iolab.net/v1/exams/0"}}}]}
public class Item
{
    public int id { get; set; }
    public string shortname { get; set; }
    public Links _links { get; set; }
}

//Rott object
public class RootObject
{
    public List<Item> items { get; set; }
}

将您的 json 解析为一个项目:

//json is the json string retrieve from the backend
//this method will convert the json to an item object if is possible
var item = JsonConvert.DeserializeObject<Item>(json);

解析项目列表:

//json is the json string retrieve from the backend
//this method will convert the json to a list of item object if is possible
var listitem =JsonConvert.DeserializeObject<List<Item>>(json);

我还为您提供了从 Web 服务调用 GET 方法的通用方法:

 //param is a get parameter and i actually optional
 public static async Task<String> RunGetAsync(string param = "")
        {
            HttpResponseMessage response = null;
            string url = "http://api.iolab.net/v1;
            string path = "/exam";
            //try catch can be deleted, i use it for timeout, task issues or web issues.
            try
            {
                using (var client = new HttpClient())
                {   
                    //create a client based in webservice url 
                    client.BaseAddress = new Uri(url);

                    client.DefaultRequestHeaders.Accept.Clear();
                    //timeout to call the backend
                    client.Timeout = TimeSpan.FromSeconds(10);
                    //if request is not allowAnonymous

                    //adding request header
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    //to create a specific path for the call
                    if (string.IsNullOrEmpty(param))
                    {
                        response = await client.GetAsync(path);
                    }
                    else
                    {
                        response = await client.GetAsync(Path + "/" + param);
                    }

                    //check if the call succeed
                    if (response.IsSuccessStatusCode)
                    {
                        //get the response into string content & return it
                        var stringContent = await response.Content.ReadAsStringAsync();
                        return stringContent;

                    }

                    return null;
                }
            }
            catch (TaskCanceledException e)
            {
                Debug.WriteLine(e.Message);
                return null;
            }
            catch (WebException we)
            {
                Debug.WriteLine(we.Message);
                return null;
            }

}

如果您有任何疑问,请不要犹豫,评论这篇文章

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM