You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android(Java)是否存在类似PHP中file_get_contents($url)的URL读取函数?

前置注意事项

  • 先在 AndroidManifest.xml 中添加网络权限:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • 所有网络请求不能放在主线程执行,否则会抛出 NetworkOnMainThreadException 异常,必须放在工作线程中运行,拿到结果后如果要更新UI再切回主线程。
  • 如果请求的是HTTP明文地址,需要在 AndroidManifest.xml 的 application 节点添加 android:usesCleartextTraffic="true",否则Android 9及以上系统会默认拦截明文请求。

原生实现方案(无需引入第三方依赖)

通过 HttpURLConnection 实现,适合不想引入额外依赖的场景:

public String fileGetContents(String urlStr) throws IOException {
    HttpURLConnection connection = null;
    InputStream inputStream = null;
    try {
        URL url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        // 超时时间可根据需求调整
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        connection.connect();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } else {
            throw new IOException("请求异常,响应码:" + connection.getResponseCode());
        }
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (connection != null) {
            connection.disconnect();
        }
    }
}

调用示例:

new Thread(() -> {
    try {
        String content = fileGetContents("https://mywebsite.com/data.php");
        // 如需更新UI,调用runOnUiThread切回主线程
        runOnUiThread(() -> {
            // 处理UI逻辑
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}).start();

第三方库实现方案(代码更简洁)

如果项目允许引入第三方依赖,使用OkHttp实现会更简单,稳定性也更高。首先在模块级 build.gradle 中添加依赖:

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.10.0'
    // 可自行替换为最新稳定版本
}

实现代码:

// 全局只需初始化一次OkHttpClient即可
OkHttpClient client = new OkHttpClient();

public String fileGetContents(String urlStr) throws IOException {
    Request request = new Request.Builder()
            .url(urlStr)
            .build();
    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful()) {
            throw new IOException("请求异常,响应码:" + response.code());
        }
        return response.body().string();
    }
}

调用逻辑和原生方案一致,需放在工作线程执行。


额外说明

如果需要读取的是大体积内容,不要直接使用以上方法,否则会造成内存溢出,需要分块写入本地存储后再分段处理。

内容的提问来源于stack exchange,提问作者whitetiger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:54:03