do Android projects, without going to the server to fetch data, typically is Android access to PHP to extract JSON data. Similar examples on the internet a lot of, and incredibly code is the same, I want to spit, you send the code is not complete, this is not deceptive.
To do this project, we need to use the dependency package (jar package) provided by Apache: ①httpclient②httpcore③http-mimi④apache-mime4j
International practice: First on the demo, download address: Android access to PHP to extract JSON data
Let's familiarize ourselves with the JSON data format under PHP
e.g.
$tnnowu = Array (' username ' = ' know matcha know ', ' password ' = ' 666 ', ' user_id ' = 1); echo Json_encode ($TNNOWU);
then we write the Java code
Mainactivity.java
Package Com.cnwuth.getjson;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.util.log;import Org.apache.http.httpresponse;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.json.jsonobject;import Java.io.bufferedreader;import Java.io.inputstreamreader;public class MainActivity Extends appcompatactivity{@Override protected void onCreate (Bundle savedinstancestate) {super.oncreate (save Dinstancestate); Setcontentview (R.layout.activity_main); private void Starturlcheck (String username,string password) {HttpClient HttpClient = new Defaulthttpclient (); StringBuilder StringBuilder = new StringBuilder (); HttpGet httpget = new HttpGet ("xxx.xxx.php"); try {HttpResponse HttpResponse = Httpclient.execute (HttpGet); BufferedReader BufferedReader = new BufferedReader (New InpuTstreamreader (Httpresponse.getentity (). GetContent ())); for (String s = bufferedreader.readline (); S!=null;s=bufferedreader.readline ()) {STRINGBUILDER.A Ppend (s); } jsonobject jsonobject = new Jsonobject (stringbuilder.tostring ()); String re_username = jsonobject.getstring ("username"); String Re_password = jsonobject.getstring ("password"); int re_user_id = Jsonobject.getint ("user_id"); Settitle ("User id_" + re_user_id); LOG.V ("url response", "true=" + re_username); LOG.V ("url response", "true=" + Re_password); } catch (Exception e) {log.v ("url response", "false"); E.printstacktrace (); } }}
Finally, network permissions are required to access the data
Androidmainifest.xml
follow me on the latest news; Sina Weibo @ Wu Tianhao Tnnowu
The above describes the Android access to PHP to extract JSON data, including aspects of the content, I hope that the PHP tutorial interested in a friend helpful.