You need to enable JavaScript to run this app. 在Kotlin中如何从指定URL列表获取GeoJson格式数据?
优惠活动
大模型
产品
解决方案
定价
更多

在Kotlin中如何从指定URL列表获取GeoJson格式数据?

Kotlin批量获取URL中GeoJson数据实现方案

1. 引入依赖

推荐使用OkHttp作为HTTP请求客户端,如果你需要直接解析GeoJson为Kotlin结构化对象,可以额外引入kotlinx序列化依赖,以下是Gradle Kotlin DSL的配置示例:

dependencies {
    // OkHttp 核心依赖,版本可替换为最新稳定版
    implementation("com.squareup.okhttp3:okhttp:4.12.0")
    // 可选:用于解析GeoJson为Kotlin对象
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.3")
}

2. 核心实现代码

OkHttpClient实例可以全局复用,避免重复创建连接池损耗性能,以下是封装好的请求方法:

import okhttp3.OkHttpClient
import okhttp3.Request
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException

// 全局复用的OkHttpClient实例
private val okHttpClient = OkHttpClient()

/**
 * 从指定URL拉取GeoJson字符串内容
 */
suspend fun fetchGeoJsonFromUrl(url: String): Result<String> = withContext(Dispatchers.IO) {
    val request = Request.Builder()
        .url(url)
        .build()

    return@withContext try {
        okHttpClient.newCall(request).execute().use { response ->
            if (!response.isSuccessful) {
                Result.failure(IOException("请求失败,响应码:${response.code}"))
            } else {
                val body = response.body?.string()
                if (body.isNullOrEmpty()) {
                    Result.failure(IOException("响应内容为空"))
                } else {
                    Result.success(body)
                }
            }
        }
    } catch (e: Exception) {
        Result.failure(e)
    }
}

3. 使用示例&注意事项

批量处理URL列表的参考代码:

import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    // 你的GeoJson URL列表
    val geoJsonUrls = listOf(
        "https://database-geojsons-test.s3.amazonaws.com/COOPERATIVES/Maps%2520test/Exploitation/Alpha/Alpha.geojson"
        // 其余URL直接追加到列表中即可
    )

    // 并发请求所有URL,提升拉取效率
    val results = geoJsonUrls.map { url ->
        async {
            val result = fetchGeoJsonFromUrl(url)
            url to result
        }
    }.awaitAll()

    // 处理请求结果
    results.forEach { (url, result) ->
        result.onSuccess { geoJsonStr ->
            println("URL $url 拉取成功,内容长度:${geoJsonStr.length}")
            // 此处可添加后续逻辑,比如解析GeoJson、存储到本地等
        }.onFailure { error ->
            println("URL $url 拉取失败:${error.message}")
        }
    }
}
  • 如果在安卓平台运行,需要先在AndroidManifest.xml中添加网络权限:<uses-permission android:name="android.permission.INTERNET" />,上述代码已通过协程切换到IO线程执行,不会阻塞主线程。
  • 大体积GeoJson建议直接读取response.body.byteStream()做流处理,边下载边写入本地文件,避免全量加载到内存引发OOM问题。
  • 拉取到的GeoJson字符串可以直接对接各类GeoJson解析库做结构化解析,不需要额外格式转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 12:15:00