android - 将 Json 和 header 发布到 REST api KOTLIN

标签 android kotlin okhttp

我找到了一个关于如何获取 url 的 youtube 视频,但我需要发布一个 REST api。我不确定该怎么做。

我试着在这里四处看看,但大部分都是 java。

fun fetchJson() {
    println ("attempting to fetch JSON")

    val url = "https://utgapi.shift4test.com/api/rest/v1/transactions/sale"

    val request = Request.Builder().url(url).build()

    val client = OkHttpClient()
    client.newCall(request).enqueue(object: Callback {
        override fun onResponse(call: Call?, response: Response?) {
            val body = response?.body()?.string()
            println(body)
            println("try and get json api working there was an error")
        }

        override fun onFailure(call: Call, e: IOException) {
            println("failed to execute request")
}

使用 GET 我只是收到一个错误,因为我没有执行 POST 请求。

最佳答案

在这里找到了一些东西 https://stackoverflow.com/a/29795501/5182150 将其转换为 Kotlin 就像

private val client = OkHttpClient();

 fun run() throws Exception {
val formBody = FormEncodingBuilder()
    .add("search", "Jurassic Park")
    .build() as RequestBody;
val request = new Request.Builder()
    .url("https://en.wikipedia.org/w/index.php")
    .post(formBody)
    .build();

val response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

System.out.println(response.body().string());
}

这应该是要点。当工作室向您发出警告时,您可以处理可为空的问题。 另一个提示是您也可以使用 Retrofit,它可以使用 OkHTTP 进行网络调用。您可以在此处找到更多关于改造的信息 https://square.github.io/retrofit/这里有一个很好的教程 https://medium.com/@prakash_pun/retrofit-a-simple-android-tutorial-48437e4e5a23

关于android - 将 Json 和 header 发布到 REST api KOTLIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56739284/

相关文章:

android - kotlin.TypeCastException : null cannot be cast to non-null type androidx. navigation.fragment.NavHostFragment 在 NavigationExtensionsKt

javascript - 如何使用 phonegap 在 android 中具有搜索功能?

javascript - Google Pixel 和 Google Pixel XL 设备的视口(viewport)宽度、高度和设备像素比是多少

android - Android:找不到声音文件

kotlin - 如何从 Kotlin 调用静态 JNI 函数?

android - Coordinatorlayout adjustResize 打开键盘时不折叠工具栏

java - OkHttp 缓存如何工作?

android - 将retrofit 2中的公共(public)路径参数替换为okhttp

java - 如何更有效地通过 http 下载大文件?

android - 模拟器在运行Helloworld程序时停在开机界面