php - 如何在我的 android 应用程序上打印 PHP echo?

标签 php android bufferedinputstream

我是 android 和 PHP 编程的新手,目前我遇到了从我的 php 页面打印 echo 语句的问题,它很简单:

    <?php
    echo "Hey there response!";
    ?>

我目前在我的 MainActivity 中使用的是:

        setContentView(R.layout.activity_main);

    TextView txtView = (TextView) findViewById(R.id.txt);

    //ASYNC WAY
    new GetData(txtView).execute("");

AsyncTask 定义为:

private class GetData extends AsyncTask<String, Void, String>{
    private TextView display;


    GetData(TextView view){
        this.display = view;
        display = (TextView) findViewById(R.id.txt);
    }

    protected String doInBackground(String... message){
        HttpClient httpclient;
        HttpGet request;
        HttpResponse response = null;
        String result = "error0";
        try{
            httpclient = new DefaultHttpClient();
            request = new HttpGet("http://localhost/php/wamp.php");
            response = httpclient.execute(request);
        } catch (Exception e){
            result = "error1";
        }

        try{
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            String line="";
            while((line = rd.readLine()) != null){
                result = result + line;
            }
        } catch(Exception e){
            result = "error2";
        }
        return result;
    }

    protected void onPostExecute(String result){
        this.display.setText(result);
    }
}

txtView 中的消息变成error2,我不知道为什么。

编辑 我最初使用非 AsyncTask 方法读取输入流,但由于网络错误,我已切换到 AsyncTask。问题仍然存在,因为我没有在我的应用程序中得到正确的回显。

最佳答案

这对 yanki 来说可能为时已晚,但对浏览此页面的其他人来说。

我用yanki的代码试了一下,得到了和他一样的错误“error 2”。然后我注意到我没有更新 list 文件以允许互联网权限。

 <uses-permission android:name="android.permission.INTERNET" />

我再次运行它,它运行良好。因此,使用 yanki 的代码并在 list 文件中输入互联网权限,该程序应该可以运行。

关于php - 如何在我的 android 应用程序上打印 PHP echo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22177821/

相关文章:

android - 如何读取 API 级别 < 18 的通知(NotificationListenerService 需要 API >= 18)

Java - 从单个 zip 文件读取多个图像并最终将它们转换为 BufferedImage 对象。好主意?

java 。 BufferedInputStream 处理图像

java - 如何将选定目录中的文件放入arraylist Android studio

php - 捕获数组中 undefined index 并创建它

php - 如何修复手机版的背景图片没有覆盖整个页面?

php - Laravel 8+ 上的 unisharp/laravel-ckeditor 无法安装包

java - 我无法更改 TextView 中的文本

用于零终止字符串的 Java BufferedReader

php - 在 codeigniter 中,出现 500 错误后重定向到自定义 html 页面