首页 > 解决方案 > 在 Android Kotlin 项目中使用 Java 11 库

问题描述

我有以下使用 Java 11 的 HttpClient 编写的 POST 请求。但 Android Studio 无法识别这些库。

import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse

class Verification {
    fun verify(username: String, signature: String) {
        try {
            HttpClient.newHttpClient().send(HttpRequest.newBuilder()
                    .POST(HttpRequest.BodyPublishers.ofString("$username:$signature"))
                    .uri(URI.create("http://localhost:9080/sse/verify"))
                    .build(), HttpResponse.BodyHandlers.ofString())
        } catch (e: Exception) {
            e.printStackTrace()
        }
}
}

build.gradle:

android {
    compileSdkVersion 29
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "io.example.code"
        minSdkVersion 26
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
...

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }
    kotlinOptions {
        jvmTarget = '11'
    }

并且在Android Studio Project StructureJDK 路径中设置为我的默认 JDKC:\Program Files\Java\jdk-11.0.8也在模块中:

在此处输入图像描述

我究竟做错了什么?如何使用 Java 11 HttpClient 实现 Http 方法?

标签: android-studiokotlingradlejava-11

解决方案


推荐阅读