[PHP] java reads data from the PHP interface, javaphp
It is similar to Android in reading json data.
PHP file:
<? Phpclass Test {// Log Path const LOG_PATH = "E: \ phpServer \ Apache \ logs \ error. log "; // number of lines displayed const PAGES = 50; public static function main () {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 function showApacheLogs () {$ test = new Test (); $ result = $ test-> readLogs (self: LOG_PATH, self: PAGES ); $ json = array (); for ($ I = 0; $ I <count ($ result); $ I ++) {$ line = $ result [$ I]; // note that json parsing will fail here $ line = str_replace ("\ r \ n", "", $ line ); $ result [$ I] = array ("num" => $ I + 1, "msg" => urlencode ($ line);} $ str = str Ipslashes (urldecode (json_encode ($ result); echo $ str;}/*** read log */private function readLogs ($ filePath, $ num = 20) {$ fp = fopen ($ filePath, "r"); $ pos =-2; $ eof = ""; $ head = false; // when the total number of rows is less than Num, determine if $ lines = array (); while ($ num> 0) {while ($ eof! = "\ N") {if (fseek ($ fp, $ pos, SEEK_END) = 0) {// return 0 if fseek is successful, -1 $ eof = fgetc ($ fp); $ pos --;} else {// when the first line arrives, set $ pos to fail fseek ($ fp, 0, SEEK_SET); $ head = true; // when the file header is reached, enable break;} array_unshift ($ lines, fgets ($ fp); if ($ head) {break;} // This sentence can only be put after the previous sentence, because after the file header is reached, read the first line and then jump out of the entire loop $ eof = ""; $ num --;} fclose ($ fp); return array_reverse ($ lines) ;}} Test: main ();
Java file:
Import java. io. inputStream; import java.net. httpURLConnection; import java.net. URL; import org. json. JSONArray; import org. json. JSONObject; public class ReadLogs {public static void main (String [] args) throws Exception {URL url = new URL ("http: // localhost/test. php? Action = showApacheLogs "); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (10000); conn. setRequestMethod ("GET"); conn. setDoInput (true); conn. setDoOutput (true); // output the returned result InputStream input = conn. getInputStream (); int resLen = 0; byte [] res = new byte [1024]; StringBuilder sb = new StringBuilder (); while (resLen = input. read (res ))! =-1) {sb. append (new String (res, 0, resLen);} String jsonStr = sb. toString (); // String to JSON JSONArray jsonArray = new JSONArray (jsonStr); for (int I = 0; I <jsonArray. length (); I ++) {JSONObject jsonObject = new JSONObject (jsonArray. getString (I); String msg = (String) jsonObject. get ("msg"); int num = (int) jsonObject. get ("num"); System. out. println (num + ":" + msg );}}}