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

Android Studio项目中无法使用java.net.http模块/包的问题

解决Android Studio中java.net.http包不存在的问题

根本原因

Android SDK 并未包含Java 11 SE中的java.net.http包,Android的运行时环境(ART)和标准JVM不同,即便Gradle JDK设置为11,Android编译和运行时也无法识别这个包。

可行解决方案

方案1:使用Android原生HttpURLConnection

这是Android内置的HTTP客户端,无需额外依赖,示例代码:

try {
    URL apiUrl = new URL("你的目标API地址");
    HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
    connection.setRequestMethod("GET"); // 根据需求设置请求方法(GET/POST等)
    
    // 读取响应
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder responseBuilder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        responseBuilder.append(line);
    }
    String responseContent = responseBuilder.toString();
    // 此处处理响应内容
    
    reader.close();
    connection.disconnect();
} catch (IOException e) {
    e.printStackTrace();
}

方案2:使用第三方HTTP库(推荐)

第三方库功能更完善,处理复杂请求(如POST、文件上传、拦截器)更方便,以OkHttp为例:

  1. 在模块级build.gradle中添加依赖:
dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.10.0'
}
  1. 示例请求代码:
OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
        .url("你的目标API地址")
        .addHeader("Content-Type", "application/json") // 根据API要求添加请求头
        .build();

// 异步请求(避免阻塞主线程)
client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(@NonNull Call call, @NonNull IOException e) {
        // 请求失败处理
        e.printStackTrace();
    }

    @Override
    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
        if (response.isSuccessful()) {
            String responseBody = response.body().string();
            // 处理响应内容,注意:此回调在子线程,更新UI需切换到主线程
        }
    }
});

额外提示

目前Android官方没有对java.net.http包提供支持,不建议尝试引入非官方兼容库,容易引发兼容性问题,优先选择上述两种成熟方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 05:15:10