Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run php script through Android app

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.

like image 292
Jignesh Chapadia Avatar asked Oct 18 '22 18:10

Jignesh Chapadia


1 Answers

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;
like image 126
jmodine Avatar answered Nov 03 '22 20:11

jmodine