知乎问题采集如此轻松,Kotlin来帮忙

175 阅读1分钟

使用 Kotlin 和 Ktor 库来调用知乎 API 的简单示例。在此之前,请确保在你的 build.gradle.kts 文件中添加了 Ktor 的依赖:

image.png

http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
dependencies {
    implementation("io.ktor:ktor-client-core:1.7.5")
    implementation("io.ktor:ktor-client-json:1.7.5")
    implementation("io.ktor:ktor-client-serialization:1.7.5")
    implementation("io.ktor:ktor-client-logging:1.7.5")
    implementation("io.ktor:ktor-client-okhttp:1.7.5")
}

然后,你可以使用以下代码来获取知乎热榜的问题列表:

import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.features.json.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*

data class ZhihuQuestion(val title: String, val url: String)

data class ZhihuHotList(val data: List<ZhihuQuestion>)

suspend fun fetchZhihuHotList(): ZhihuHotList {
    val client = HttpClient(OkHttp) {
        install(JsonFeature) {
            serializer = KotlinxSerializer()
        }
    }

    return try {
        val response: HttpResponse = client.get("https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total")
        if (response.status.isSuccess()) {
            client.receive()
        } else {
            throw Exception("Failed to fetch Zhihu hot list: ${response.status}")
        }
    } finally {
        client.close()
    }
}

suspend fun main() {
    val zhihuHotList = fetchZhihuHotList()

    for ((index, question) in zhihuHotList.data.withIndex()) {
        println("${index + 1}. ${question.title}")
        println("   URL: ${question.url}")
        println("=".repeat(50))
    }
}

请注意,知乎的 API 使用 OAuth2 鉴权,你可能需要进一步研究如何进行授权。在实际应用中,你可能还需要解析 API 响应的其他字段以获取更多信息。