And Android is a reason to read JSON data
PHP Files:
<?PHPclasstest{//Log Path ConstLog_path= "E:\phpServer\Apache\logs\\error.log"; //number of rows displayed ConstPages=50; Public Static functionMain () {Header("Content-type:text/html;charset=utf-8"); if(!Empty($_get[' Action '])){ if(!method_exists(' Test ',$_get[' Action '])){ Echo"404"; }Else{ Self::$_get[' Action '](); } Exit; } } Public Static functionshowapachelogs () {$test=NewTest (); $result=$test->readlogs (self::log_path,self::PAGES); $json=Array(); for($i= 0;$i<Count($result);$i++){ $line=$result[$i]; //note here that JSON parsing fails if processing $line=Str_replace("\ r \ n", "",$line); $result[$i]=Array("num" =$i+1, "msg" =UrlEncode($line)); } $str=stripslashes(UrlDecode(Json_encode ($result))); Echo $str; } /** * Read log*/ Private functionReadlogs ($filePath,$num=20){ $fp=fopen($filePath, "R"); $pos=-2; $eof= ""; $head=false;//when the total number of rows is less than NUM, the first row is judged $lines=Array(); while($num>0){ while($eof! = "\ n"){ if(fseek($fp,$pos, seek_end) ==0) {//Fseek successfully returned 0, failed to return-1 $eof=fgetc($fp); $pos--; }Else{//setting $pos fails when the first line is reached at the beginning of the row fseek($fp, 0,seek_set); $head=true;//reach the head of the file, switch open Break; } } Array_unshift($lines,fgets($fp)); if($head){ Break; }//this sentence, can only put a sentence after, because to the file header, the first line read out and then jump out of the entire loop $eof= ""; $num--; } fclose($fp); return Array_reverse($lines); }}test:: Main ();
Java files:
ImportJava.io.InputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL;ImportOrg.json.JSONArray;ImportOrg.json.JSONObject; Public classReadlogs { Public Static voidMain (string[] args)throwsException {URL url=NewURL ("Http://localhost/test.php?action=showApacheLogs"); HttpURLConnection Conn=(HttpURLConnection) url.openconnection (); Conn.setconnecttimeout (10000); Conn.setrequestmethod ("GET"); Conn.setdoinput (true); Conn.setdooutput (true); //output return resultInputStream input =Conn.getinputstream (); intReslen =0; byte[] res =New byte[1024]; StringBuilder SB=NewStringBuilder (); while(Reslen=input.read (res))!=-1) {sb.append (NewString (res, 0, Reslen)); } String jsonstr=sb.tostring (); //string into JSONJsonarray jsonarray=NewJsonarray (JSONSTR); for(intI=0;i<jsonarray.length (); i++) {Jsonobject jsonobject=NewJsonobject (jsonarray.getstring (i)); String msg= (String) jsonobject.get ("MSG")); intNum= (int) jsonobject.get ("num"); SYSTEM.OUT.PRINTLN (Num+":"+msg); } }}
[PHP] Java reads PHP interface data