Run php script through Android app

Jignesh Chapadia picture Jignesh Chapadia · Jan 9, 2016 · Viewed 7.2k times · Source

I have a php script stored in Xampp server, and want that my application execute it to perform a task. In eclipse nothing happend with android.txt at server side. The following is my code for android app

String url = "http://my.site.php?data=hello";
    HttpClient client = new DefaultHttpClient();
    try {
      client.execute(new HttpGet(url));
    } catch(IOException e) {
      //do something here
    }

following is my php code at server side.

 $name=$_GET['data'];
    $file=fopen("./android.txt","w");
    fwrite($file, $name);
    fclose($file);

Though I am running php from mozila browser, it works fine. but this code is not working for android.

Answer

jmodine picture jmodine · Jan 9, 2016

Try something like this you don't an open connection yet nor do you have a reader to read a response. Now it is prefered to run a external connection on an AsyncTask then return the response to a main thread. Set the response to be viewed as a EditText or an alert dialog so you can see any errors the server may be giving you also.

 URL url = "http://my.site.php?data=hello"
 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        String line;
        StringBuilder sb= new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        while ((line=br.readLine()) != null) {
            sb.append(line);
            response =sb.toString();
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return response;