App-based apps are sure to interact with the Web, so this section will be a real-world Android access to the network API, or the use of the previous section of the demo:
First, prepare the API:
JSON is generally used as a data interchange format, and currently all languages can output JSON strings.
If you use PHP to output a simple JSON, you can write this:
<? PHP $arr Array (' users ' = =array(' Mady ', ' 123 ')); echo json_encode ($arr);? >
The output JSON is as follows:
{"Users": ["Mady", "123"]}
You can also use VS to create an API to serialize an array directly, or any other way as long as the data is properly formatted.
Second, the implementation of network API access:
The first access to the network requires authorization, that is, the installation to remind the part of the tick:
Open Bin/res/androidmanifest.xml Add an authorization request node below the root node:
<android:name= "Android.permission.INTERNET"/>
Then there is access to the network, here is a section from the Internet to access the class:
Importorg.apache.http.HttpEntity;ImportOrg.apache.http.HttpResponse;ImportOrg.apache.http.HttpStatus;Importorg.apache.http.client.HttpClient;ImportOrg.apache.http.client.methods.HttpPost;Importorg.apache.http.impl.client.DefaultHttpClient;Importorg.apache.http.util.EntityUtils; Public classhttputils{/** * @paramServer URL address for path request *@paramencode encoded format *@returnconverts the data returned from the server side into a string*/ Public Staticstring Sendpostmessage (string path, string encode) {string result= ""; HttpClient HttpClient=Newdefaulthttpclient (); Try{httppost HttpPost=Newhttppost (path); HttpResponse HttpResponse=Httpclient.execute (HttpPost); if(Httpresponse.getstatusline (). Getstatuscode () = =HTTPSTATUS.SC_OK) {httpentity httpentity=httpresponse.getentity (); if(Httpentity! =NULL) {result=entityutils.tostring (httpentity, encode); } } } Catch(Exception e) {e.printstacktrace (); } finally{Httpclient.getconnectionmanager (). Shutdown (); } returnresult; }}
There is also a JSON parsing class from the Web, using the Android-brought parsing library:
Importjava.util.ArrayList;Importjava.util.List;ImportOrg.json.JSONArray;ImportOrg.json.JSONObject; Public classjsonutil{/** * @paramcitiesstring JSON string data obtained from server side *@returnparse the JSON string data into the list*/ Public StaticList<string>parsecities (String citiesstring) {List<String> cities =NewArraylist<string>(); Try{jsonobject Jsonobject=NewJsonobject (citiesstring); Jsonarray Jsonarray= Jsonobject.getjsonarray ("Users"); for(inti = 0; I < jsonarray.length (); i++) {Cities.add (jsonarray.getstring (i)); } } Catch(Exception e) {e.printstacktrace (); } returncities; }}
Finally, it is important to note that access to the network in Android must be asynchronous, synchronous direct error, so you need to increase the asynchronous access:
Public classMyasynctaskextendsAsynctask<string, Void, list<string>>{@Overrideprotected voidOnPreExecute () {Super. OnPreExecute (); } @OverrideprotectedList<string>doinbackground (String ... params) {List<String> cities =NewArraylist<string>(); String citiesstring= Httputils.sendpostmessage (Params[0], "Utf-8"); Cities=jsonutil.parsecities (citiesstring); returncities; } @Overrideprotected voidOnPostExecute (list<string>result) {TextView Lblinfo=(TextView) Findviewbyid (r.id.form_title); EditText Txt_login_name=(EditText) Findviewbyid (r.id.txt_login_name); EditText Txt_login_pass=(EditText) Findviewbyid (R.ID.TXT_LOGIN_PWD); String LoginName=Txt_login_name.gettext (). toString (). Trim (); String Loginpass=Txt_login_pass.gettext (). toString (). Trim (); if(Loginpass.equals (Result.get (1)) &&loginname.equals (result.get (0)) {Lblinfo.settext ("Login Successful!" "); } Else{Lblinfo.settext ("Login failed!" "); } Super. OnPostExecute (Result); } }
Divided into pre-access, access, after access (estimated to be convenient to increase the progress bar), we add the processing code after the visit, and then in the previous section of the button click event Reduction:
Private Final String City_path_json = "http://192.168.1.6:89/Login2.php"; Public void Btn_click (View v) { new myasynctask (). Execute (City_path_json); }
The only description required: The result type after access is the return value type in the Access
The only thing that needs to be said is that the API must be set up on another machine and must use IP access because localhost and 127 are used by the simulator themselves.
First look at the login user name and password is what, access to the following API:
To run the app:
Enter the correct information:
. NET Programmer Android Learning Path 2: Accessing the network API