HttpURLConnection
URL url = new URL("https://api.example.com/data"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); if (responseCode == 200) { InputStream inputStream = connection.getInputStream(); // 读取输入流并解析数据 }
OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://api.example.com/data") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) {} @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String responseBody = response.body().string(); // 解析数据 } } });
库名 | 特点 | 适用场景 |
---|---|---|
Retrofit | 基于 OkHttp,支持注解、自动解析 JSON/XML、支持 RxJava | 复杂 API 调用、强类型安全 |
Volley | 轻量级、支持图片加载、内置缓存机制 | 简单请求、快速开发 |
OkHttp | 高性能、支持 WebSocket、拦截器机制 | 需要自定义网络逻辑的场景 |
Fetch API | Android 12+ 提供的原生 API,支持 Promise 风格 | 新项目且兼容高版本系统 |
AsyncTask
)viewLifecycleOwner.lifecycleScope.launch { val result = withContext(Dispatchers.IO) { // 网络请求或耗时操作 } // 更新UI }
// 在 ViewModel 中发起请求 liveData.postValue(fetchDataFromNetwork());
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class) .setConstraints(Constraints.connectivityConstraint(ConnectivityType.CONNECTED)) .build(); WorkManager.getInstance(context).enqueue(workRequest);
Gson gson = new Gson(); MyData[] data = gson.fromJson(jsonString, MyData[].class);
val moshi = Moshi.Builder().build() val jsonAdapter = moshi.adapter(MyData::class.java) val data = jsonAdapter.fromJson(jsonString)
存储方式 | 特点 | 适用场景 |
---|---|---|
SharedPreferences | 轻量级键值对存储 | 简单配置信息 |
SQLite/Room | 结构化数据存储、支持复杂查询 | 离线数据持久化 |
DataStore | Jetpack 提供的轻量级键值存储(替代 SP) | 现代替代方案,支持协议 |
AndroidManifest.xml
中添加: <uses-permission android:name="android.permission.INTERNET" />
OkHttpClient client = new OkHttpClient.Builder() .sslSocketFactory(new TrustManagerFactory().trustManagers(TrustManagerFactory.getDefaultAlgorithm())) .hostnameVerifier((hostname, session) -> true) .build();
lifecycleScope.launch
或 viewModelScope
在后台线程执行任务,自动切换到主线程更新 UI。LiveData
观察数据变化并自动更新 UI。