当前位置:   article > 正文

【Android实践一】如何调用后端接口_安卓调用后端接口

安卓调用后端接口

一、准备工作

1、build.gradle 配置文件引入 okhttp

dependencies {
	...
    implementation("com.squareup.okhttp3:okhttp:4.10.0")
    implementation 'cn.hutool:hutool-all:5.8.4'

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

使用 viewBinding 注意:顺便加下 buildFeatures

android {
    compileSdk 31
	...
    buildFeatures {
        viewBinding true
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2、AndroidManifest.xml 配置放开网络权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.luna.apitest">

    <!--  网络权限  -->
    <uses-permission android:name="android.permission.INTERNET" />
    
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.APITest">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

二、调用接口

1、布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_show_get"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="40dp"
        android:gravity="center"
        android:hint="通过网络请求获取到的内容"
        android:padding="5dp" />

    <Button
        android:id="@+id/bt_send_get"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="GET发送请求" />

    <TextView
        android:id="@+id/tv_show_post"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="40dp"
        android:gravity="center"
        android:hint="通过网络请求获取到的内容"
        android:padding="5dp" />

    <Button
        android:id="@+id/bt_send_post"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="POST发送请求" />

</LinearLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

2、新建单例工具类

object OkHttpUtil {

    fun get(url: String, callback: Callback) {
        Thread {
            val client: OkHttpClient = OkHttpClient.Builder().build()
            val request: okhttp3.Request = okhttp3.Request.Builder()
                .url(url)
                .build()
            client.newCall(request).enqueue(callback)
        }.start()
    }

    fun post(url: String, json: String, callback: Callback) {
        Thread {
            val requestBody: RequestBody =
                json.toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
            val client: OkHttpClient = OkHttpClient.Builder().build()
            val request: okhttp3.Request = okhttp3.Request.Builder()
                .url(url)
                .post(requestBody)
                .build()
            client.newCall(request).enqueue(callback)
        }.start()
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

3、Activity 调用接口实现

package com.luna.apitest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import cn.hutool.json.JSONObject
import cn.hutool.json.JSONUtil
import com.luna.apitest.databinding.ActivityMainBinding
import com.luna.apitest.util.OkHttpUtil
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        //加载布局
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // get接口:按钮点击事件
        binding.btSendGet.setOnClickListener {
            OkHttpUtil.get("https://api.iyk0.com/twqh", object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    runOnUiThread {
                        Runnable {
                            Log.d("MainActivity", "请求失败!")
                        }
                    }
                }

                override fun onResponse(call: Call, response: Response) {
                    val data = response.body?.string().toString()
                    showData(data)
                    Log.d("MainActivity", "获取到的数据为:$data")
                }
            })
        }

        // post接口:按钮点击事件
        val json: String = "{\n" +
                "  \"id\": 0,\n" +
                "  \"category\": {\n" +
                "    \"id\": 0,\n" +
                "    \"name\": \"string\"\n" +
                "  },\n" +
                "  \"name\": \"doggie\",\n" +
                "  \"photoUrls\": [\n" +
                "    \"string\"\n" +
                "  ],\n" +
                "  \"tags\": [\n" +
                "    {\n" +
                "      \"id\": 0,\n" +
                "      \"name\": \"string\"\n" +
                "    }\n" +
                "  ],\n" +
                "  \"status\": \"available\"\n" +
                "}"
        binding.btSendPost.setOnClickListener {
            OkHttpUtil.post("https://petstore.swagger.io/v2/pet", json, object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    runOnUiThread {
                        Runnable {
                            Log.d("MainActivity", "请求失败!")
                        }
                    }
                }

                override fun onResponse(call: Call, response: Response) {
                    val data = response.body?.string().toString()
                    showDataPost(data)
                    Log.d("MainActivity", "获取到的数据为:$data")
                }
            })
        }


    }

    private fun showDataPost(data: String) {
        val data: JSONObject = JSONUtil.parseObj(data)
        binding.tvShowPost.text = data.getStr("id")
    }

    private fun showData(data: String) {
        binding.tvShowGet.text = data
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91

如存在问题,请在评论区指出留言,感谢!

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/264944?site
推荐阅读
相关标签
  

闽ICP备14008679号