Android 与 php 交互

标签 android

我有问题!我连接了一个 php 页面以连接数据库,该方法在 Froyo 上运行良好,但在较新版本的 Android 上不起作用。有什么问题?

        public static String interact(String request){
            String result="test";
        String site = "http://xxxx.net:nnn/xxx";
        URL url = new URL(site);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.connect();

        OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
        wr.write(request);
        wr.flush();
        wr.close();

        Scanner in = new Scanner(connection.getInputStream());
        while(in.hasNextLine())
        result+=in.nextLine();
        connection.disconnect();
        return result;

    }
    catch (UnknownHostException e) {
        return e.getMessage();
    } catch (IOException ex) {
        return ex.getMessage();
    }
    catch (Exception ex){
        return ex.getMessage();
    }

}   

我需要发送数据并获得响应,但在比 2.2 更高的 Android 上它只会给我 null。

最佳答案

您正在主线程上运行网络请求

Android >=3.0 不允许这样做。你需要使用 AsyncTask调用网络请求

关于Android 与 php 交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13591294/

相关文章:

android - Jetpack Compose 自定义徽章与 CircleShape 的动态文本大小未正确绘制

java - 如何将文件写入 Android 中的外部公共(public)存储以便它们在 Windows 中可见?

Android MediaCodec 无法解码 wma 文件

android - 无法在 Android 的 ndk-gdb 中达到断点

android - 网络调用报警超时

android - 在 Recyclerview 中多次调用 onClick

SimonVT menuDrawer 中出现 java.lang.NullPointerException?

android - 迁移到 androidX 后出现 Manifest marge error

android - 如何更改最近的搜索图标(SearchManager.SUGGEST_COLUMN_ICON_1 列)

java - 安卓倒计时不工作