First look at the effect, note: (1) here because my simulator does not support Chinese input, so, for this, I am directly in the code to write dead my query city, in the code below I do not have to query the city to write dead.
(2) If the reader wants to successfully use all the code of this example (that is, it is too lazy to change it!) ), need the reader to apply for a key, and then put in my code, the following code comments I also said, please watch carefully.
(3) To change the code of my pro-test feasible, there is a picture of the truth.
(4) This article is all original, warmly welcome the majority of users to share this article, but please indicate the source. I also welcome you and I actively exchange relevant knowledge.
Layout as you can see, very humble, I do not post code AH.
Activity code:
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; A label that shows the JSON data after a successful query
EditText City; An input box to receive the parameters to be passed, which I use to pass the name of the city.
String querycity = ""; Record the contents of the input box
String Url = "Http://apis.haoservice.com/weather";//Service address requested
protected override void OnCreate (bundle bundle)
{
Base. OnCreate (bundle);
Set our view from the "main" layout resource
Setcontentview (Resource.Layout.Main);
Get our buttons 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, "Please enter the city name!") ", Toastlength.long). Show ();
Return
}
querycity = City. Text;
String Body = "Cityname=" +system.web.httputility.urlencode (querycity) + "&key=";//special attention, this requires the reader to apply for a key and then fill in
byte[] data = Encoding.ASCII.GetBytes (Body); Convert to byte array
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;
});
/* Here are 2 ways to get rid of whitespace inside the string, JSON data is not allowed to have special characters inside otherwise parsing will go wrong
**/
string test1 = result. Replace ("", ""); Remove spaces
String test = Regex.Replace (result, @ "\s", "");//Remove space carriage return and other special characters here test1 and test content is the same, I just enumerate 2 different methods
/* The first parsing JSON method: Deserializing an indexer using Json.NET Access official website address: Http://www.newtonsoft.com/json
The corresponding is serialization: string json = Jsonconvert.serializeobject (Team), where team is the JSON object
*/
var results = Jsonconvert.deserializeobject (test1);//deserialization, which can be accessed through an indexer, to complete the parsing of JSON
You can then access any of the data in the JSON you want with the results indexed method.
}
catch (System.Exception sysexc)
{
Android.Util.Log.Error ("http Response", "Exception:" + sysexc.message);
This. Runonuithread (() = TV. Text = "Exception:" + sysexc.message);
}
}
}
}
Mono for Android access to WebService and WEBAPI as well as get and parse JSON