通过 Android 应用程序运行 php 脚本

Jig*_*dia 5 php android androidhttpclient

我有一个存储在 Xampp 服务器中的 php 脚本,并希望我的应用程序执行它来执行任务。在 Eclipse 中,服务器端的 android.txt 没有发生任何事情。以下是我的android应用程序代码

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

以下是我在服务器端的 php 代码。

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

虽然我从 mozila 浏览器运行 php,但它运行良好。但此代码不适用于 android。

小智 3

尝试这样的事情,你还没有开放的连接,也没有读者来阅读回复。现在,首选在 AsyncTask 上运行外部连接,然后将响应返回到主线程。将响应设置为以 EditText 或警报对话框的形式查看,以便您可以看到服务器可能向您提供的任何错误。

 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;
Run Code Online (Sandbox Code Playgroud)