Android集成GLM-4.7完整教程:30分钟实现AI对话功能

╔═══════════════════════════════════════════════════════════════════════╗
║                                                                           ║
║   ╔══════════╗                                                        ║
║   ║  📱         ║     Android集成GLM-4.7完整教程                          ║
║   ║             ║                                                        ║
║   ║  ┌─────────┐ ║     30分钟实现AI对话功能                             ║
║   ║  │ 🤖 AI  │ ║                                                        ║
║   ║  └─────────┘ ║                                                        ║
║   ║             ║     [Android] [GLM-4.7] [Kotlin] [Retrofit]            ║
║   ╚══════════╝                                                        ║
║                                                                           ║
╚═════════════════════════════════════════════════════════════════════════╝

你遇到过这个问题吗?

想在Android应用里加入AI对话功能,但被GLM-4.7 API集成搞得焦头烂额?

你遇到的问题可能是:

  • 不知道怎么正确调用GLM-4.7 API
  • Android网络请求总是超时或失败
  • 异步处理搞得界面卡顿
  • API响应格式解析出错
  • 错误处理写得一塌糊涂

别担心,这篇文章手把手教你从零开始,在30分钟内完成Android应用中GLM-4.7的集成。

Android集成GLM-4.7的核心问题分析

为什么在Android中调用GLM-4.7 API这么麻烦?

核心痛点有三个:

  1. 网络权限问题 - Android从Android 9.0开始默认禁用HTTP明文传输,需要配置网络安全
  2. 异步调用复杂性 - Android主线程不能做网络请求,需要使用Kotlin协程或RxJava
  3. API调用细节多 - 鉴权、参数格式、响应解析,每个环节都可能出错

好消息是,掌握了正确的方法,这些都能轻松解决。

解决方案:Android集成GLM-4.7完整实现

步骤1:准备工作

1.1 项目依赖配置

在app模块的build.gradle中添加必要依赖:

dependencies {
    // 网络请求库 - Retrofit用于Android GLM-4.7 API调用
    implementation 'com.squareup.retrofit2:retrofit:2.11.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.11.0'
    implementation 'com.squareup.okhttp3:okhttp:4.12.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0'

    // Kotlin协程支持 - 处理Android异步网络请求
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.0'

    // JSON解析库
    implementation 'com.google.code.gson:gson:2.11.0'
}

// 版本兼容性说明:
// - Retrofit 2.11.0 官方推荐搭配 OkHttp 4.12.0
// - 如果使用旧版 Retrofit (2.9.x),需搭配 OkHttp 4.10.x
// - 版本不匹配可能导致:适配器加载失败、HTTP/2不支持等问题
// - 协程 1.8.0 需要 Kotlin 1.9.0+,建议同步升级 Kotlin 插件版本
1.2 Android网络权限配置

AndroidManifest.xml中添加网络权限:

<!-- Android网络权限配置 - GLM-4.7 API调用必需 -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

注意: 如果使用HTTPS,无需额外配置;如果使用HTTP,需要在res/xml/network_security_config.xml中配置:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <!-- Android网络安全配置 - 允许HTTP明文传输 -->
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">your-api-domain.com</domain>
    </domain-config>
</network-security-config>

然后在Manifest中引用:

<application
    android:networkSecurityConfig="@xml/network_security_config"
    ...>
1.3 创建GLM-4.7数据模型
                        GLM-4.7 数据模型

┌─────────────────────────────────────────────────────────────────────────────┐
│                              请求模型                                     │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│  data class GLMRequest(                                                   │
│      val model: String = "glm-4.7",      // 模型版本                     │
│      val messages: List<Message>,           // 消息列表                    │
│      val temperature: Float = 0.7f,       // 0-2(官方范围),控制生成随机性 │
│      val max_tokens: Int = 1024           // 默认值降低,避免触发限流      │
│  )                                                                         │
│                                                                           │
│  data class Message(                                                       │
│      val role: String,              // "user" | "assistant" | "system"  │
│      val content: String            // 消息内容                          │
│  )                                                                         │
│                                                                           │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│                              响应模型                                     │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│  data class GLMResponse(                                                  │
│      val id: String,                  // 请求ID                          │
│      val choices: List<Choice>,      // AI回复选项                        │
│      val usage: Usage?                // Token使用统计                   │
│  )                                                                         │
│                                                                           │
│  data class Choice(                                                        │
│      val index: Int,                  // 选项索引                         │
│      val message: Message,           // AI消息                          │
│      val finish_reason: String?       // 结束原因                         │
│  )                                                                         │
│                                                                           │
│  data class Usage(                                                         │
│      val prompt_tokens: Int,          // 输入token数                     │
│      val completion_tokens: Int,      // 输出token数                     │
│      val total_tokens: Int            // 总token数                        │
│  )                                                                         │
│                                                                           │
└─────────────────────────────────────────────────────────────────────────────┘

定义GLM-4.7 API请求和响应的数据类:

// GLM-4.7 API请求模型
data class GLMRequest(
    val model: String = "glm-4.7",
    val messages: List<Message>,
    val temperature: Float = 0.7f,  // 0-2(官方范围),控制生成随机性
    val max_tokens: Int = 1024        // 降低默认值,避免触发限流
)

// GLM-4.7消息模型
data class Message(
    val role: String,  // "user", "assistant", "system"
    val content: String
)

// GLM-4.7 API响应模型
data class GLMResponse(
    val id: String,
    val choices: List<Choice>,
    val usage: Usage?
)

// GLM-4.7选择模型
data class Choice(
    val index: Int,
    val message: Message,
    val finish_reason: String?
)

// GLM-4.7 Token使用统计
data class Usage(
    val prompt_tokens: Int,
    val completion_tokens: Int,
    val total_tokens: Int
)

// 参数详细说明:
// temperature: 0-2(官方范围)
//   - 0-0.3:确定性输出,适合代码生成、逻辑推理
//   - 0.3-0.7:平衡输出,适合对话、问答
//   - 0.7-1.3:创造性输出,适合写作、头脑风暴
//   - 1.3-2.0:高度随机,仅适用于特殊场景
// max_tokens: 512-4096
//   - 512-1024:简单问答、短对话(推荐默认值)
//   - 1024-2048:中等长度对话
//   - 2048-4096:长对话、复杂任务
//   - ⚠️ 设置过高可能导致 API 限流(429 Too Many Requests)

步骤2:核心实现 - Retrofit异步网络请求

                    Android GLM-4.7 集成架构

┌─────────────────────────────────────────────────────────────────────────────┐
│                           Android应用架构                                  │
└─────────────────────────────────────────────────────────────────────────────┘

  [用户界面]          [ViewModel层]          [数据层]            [API层]
      │                    │                  │                  │
      │ sendMessage()      │                  │                  │
      ├────────────────────>│                  │                  │
      │                    │ chat()           │                  │
      │                    ├──────────────────>│                  │
      │                    │                  │ chatCompletion()  │
      │                    │                  ├──────────────────>│
      │                    │                  │  ┌────────────┐   │
      │                    │                  │  │  GLM-4.7   │   │
      │                    │                  │  │  API       │   │
      │                    │                  │  └────────────┘   │
      │                    │                  │         │         │
      │                    │                  │         │ GLMResponse
      │                    │                  │         │         │
      │                    │                  │<────────┘         │
      │                    │ Result<String>    │                  │
      │                    │<─────────────────┘                  │
      │  UI State更新      │                                     │
      │<───────────────────┘                                     │
      ▼                                                        │
  [显示响应]                                                     │
                                                              │
技术栈:Kotlin Coroutines + Retrofit + OkHttp + GLM-4.7 API  │
2.1 创建GLM-4.7 Retrofit API接口
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Header
import retrofit2.http.POST

// Android GLM-4.7 API接口定义
interface GLMApiService {
    @POST("v4/chat/completions")  // 根据官方文档确认路径
    suspend fun chatCompletion(
        @Header("Authorization") authorization: String,
        @Header("Content-Type") contentType: String = "application/json",
        @Body request: GLMRequest
    ): Response<GLMResponse>

    companion object {
        // GLM-4.7 API创建方法 - 配置OkHttp和Retrofit
        
        // ⚠️ API 路径说明:
        // 智谱AI官方推荐 Base URL: https://open.bigmodel.cn/api/
        // 如果使用旧版 API 路径,可能是: https://open.bigmodel.cn/api/paas/v4/
        // 建议使用官方最新文档确认: https://open.bigmodel.cn/dev/api
        
        // 当前配置(推荐):
        fun create(baseUrl: String = "https://open.bigmodel.cn/api/"): GLMApiService {
            val loggingInterceptor = HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            }

            // OkHttp配置 - 处理Android网络请求超时和重试
            val okHttpClient = OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)  // 启用连接失败重试
                .build()

            // Retrofit配置 - 用于Android GLM-4.7 API调用
            return Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(GLMApiService::class.java)
        }
    }
}

// 错误处理说明:
// 如果遇到 404 错误,检查:
// 1. Base URL 是否正确
// 2. API 路径是否包含 /paas/ 前缀(旧版)
// 3. @POST 注解路径是否为 "v4/chat/completions"
2.2 创建GLM-4.7 API客户端类
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

// Android GLM-4.7客户端 - 使用Kotlin协程处理异步网络请求
class GLMClient(private val apiKey: String) {

    private val apiService = GLMApiService.create()
    private val authorization = "Bearer $apiKey"

    // GLM-4.7聊天方法 - Android异步网络请求实现
    suspend fun chat(
        userMessage: String,
        systemPrompt: String = "你是一个有用的AI助手。",
        conversationHistory: List<Message> = emptyList()
    ): Result<String> = withContext(Dispatchers.IO) {
        try {
            // 构建GLM-4.7消息列表
            val messages = mutableListOf<Message>()

            // 添加系统提示
            if (systemPrompt.isNotEmpty()) {
                messages.add(Message(role = "system", content = systemPrompt))
            }

            // 添加历史对话 - GLM-4.7多轮对话上下文支持
            messages.addAll(conversationHistory)

            // 添加用户消息
            messages.add(Message(role = "user", content = userMessage))

            // 发起GLM-4.7 API请求
            val request = GLMRequest(
                model = "glm-4.7",
                messages = messages,
                temperature = 0.7f,
                max_tokens = 1024  // 降低默认值,避免触发限流
            )

            val response = apiService.chatCompletion(authorization, "application/json", request)

            if (response.isSuccessful && response.body() != null) {
                val assistantMessage = response.body()!!.choices.firstOrNull()?.message?.content
                if (assistantMessage != null) {
                    Result.success(assistantMessage)
                } else {
                    Result.failure(Exception("GLM-4.7响应中未找到有效消息"))
                }
            } else {
                val errorMsg = response.errorBody()?.string() ?: "未知错误"
                Result.failure(Exception("GLM-4.7 API请求失败: $errorMsg"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
    }

    // GLM-4.7流式响应 - 高级功能
    suspend fun streamChat(
        userMessage: String,
        onTokenReceived: (String) -> Unit,
        onComplete: (String) -> Unit,
        onError: (Exception) -> Unit
    ) {
        // 注意: GLM-4.7流式响应实现更复杂
        // 实际项目建议使用WebSocket或SSE库
    }
}
2.3 在ViewModel中使用Kotlin协程
                    Android GLM-4.7 集成数据流程

┌─────────────┐      ┌─────────────┐      ┌─────────────┐      ┌─────────────┐
│   用户      │      │  ViewModel  │      │  GLMClient  │      │  GLM-4.7    │
│   输入      │      │             │      │             │      │   API       │
└──────┬──────┘      └──────┬──────┘      └──────┬──────┘      └──────┬──────┘
       │                    │                    │                    │
       │ "你好"             │                    │                    │
       ├────────────────────>│                    │                    │
       │                    │                    │                    │
       │                    │                    │                    │
       │                    │ chat("你好")       │                    │
       │                    ├────────────────────>│                    │
       │                    │                    │ 构建消息列表        │
       │                    │                    │                    │
       │                    │                    │ HTTP Request       │
       │                    │                    ├────────────────────>│
       │                    │                    │                    │
       │                    │                    │                    │ 处理
       │                    │                    │                    │
       │                    │                    │                    │
       │                    │                    │                    │
       │                    │                    │<────────────────────┤
       │                    │                    │ HTTP Response      │
       │                    │                    │                    │
       │                    │                    │                    │
       │                    │ Result.success()   │                    │
       │                    │<────────────────────┤                    │
       │                    │                    │                    │
       │ 更新UI             │                    │                    │
       │<────────────────────┤                    │                    │
       │                    │                    │                    │
       ▼                    ▼                    ▼                    ▼
   显示AI响应        State更新          请求完成           响应返回

┌────────────────────────────────────────────────────────────────────────────┐
│ 关键特性:                                                                  │
│ • Kotlin Coroutines处理异步请求                                           │
│ • Retrofit封装HTTP调用                                                     │
│ • OkHttp配置超时和重试                                                     │
│ • Result类型处理成功/失败                                                   │
└────────────────────────────────────────────────────────────────────────────┘
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

// Android聊天UI状态
data class ChatUiState(
    val isLoading: Boolean = false,
    val response: String = "",
    val error: String? = null,
    val conversation: List<Pair<String, String>> = emptyList()
)

// GLM-4.7聊天ViewModel - 使用Kotlin协程处理异步请求
class ChatViewModel(private val glmClient: GLMClient) : ViewModel() {

    private val _uiState = MutableStateFlow(ChatUiState())
    val uiState: StateFlow<ChatUiState> = _uiState.asStateFlow()

    // 发送消息 - Android异步网络请求
    fun sendMessage(message: String) {
        if (message.isBlank()) return

        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(
                isLoading = true,
                error = null
            )

            glmClient.chat(message).fold(
                onSuccess = { response ->
                    val newConversation = _uiState.value.conversation + (message to response)
                    _uiState.value = _uiState.value.copy(
                        isLoading = false,
                        response = response,
                        conversation = newConversation
                    )
                },
                onFailure = { error ->
                    _uiState.value = _uiState.value.copy(
                        isLoading = false,
                        error = error.message ?: "未知错误"
                    )
                }
            )
        }
    }
}
2.4 创建Android UI界面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">

    <!-- Android对话历史显示 -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/chatRecyclerView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <!-- GLM-4.7响应显示 -->
    <TextView
        android:id="@+id/responseTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:padding="12dp"
        android:background="@drawable/response_background"
        android:text="等待输入..."
        android:textSize="14sp" />

    <!-- 加载状态 -->
    <ProgressBar
        android:id="@+id/loadingProgressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone" />

    <!-- Android输入框 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="8dp">

        <EditText
            android:id="@+id/messageEditText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="输入消息..."
            android:maxLines="4" />

        <Button
            android:id="@+id/sendButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="发送" />
    </LinearLayout>

</LinearLayout>
2.5 Android Activity实现
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch

// Android聊天Activity - GLM-4.7集成完整实现
class ChatActivity : AppCompatActivity() {

    private lateinit var binding: ActivityChatBinding
    private val viewModel: ChatViewModel by viewModels {
        val apiKey = "your-api-key-here"  // 从安全存储中获取
        ChatViewModelFactory(GLMClient(apiKey))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityChatBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setupObservers()
        setupListeners()
    }

    private fun setupObservers() {
        lifecycleScope.launch {
            viewModel.uiState.collect { state ->
                // 更新加载状态
                binding.loadingProgressBar.visibility =
                    if (state.isLoading) View.VISIBLE else View.GONE

                // 更新GLM-4.7响应文本
                binding.responseTextView.text =
                    if (state.response.isEmpty()) "等待输入..." else state.response

                // 显示错误
                if (state.error != null) {
                    Toast.makeText(
                        this@ChatActivity,
                        "错误: ${state.error}",
                        Toast.LENGTH_SHORT
                    ).show()
                }

                // 更新Android对话历史(需要实现RecyclerView适配器)
                // binding.chatRecyclerView.adapter?.submitList(state.conversation)
            }
        }
    }

    private fun setupListeners() {
        binding.sendButton.setOnClickListener {
            val message = binding.messageEditText.text.toString().trim()
            if (message.isNotEmpty()) {
                viewModel.sendMessage(message)
                binding.messageEditText.text?.clear()
            }
        }
    }
}

// Android ViewModelFactory
class ChatViewModelFactory(private val glmClient: GLMClient) :
    ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(ChatViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return ChatViewModel(glmClient) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

步骤3:测试验证

3.1 Android单元测试
import kotlinx.coroutines.test.runTest
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test

// GLM-4.7 Android单元测试
class GLMClientTest {

    private lateinit var glmClient: GLMClient

    @Before
    fun setup() {
        // 使用测试API密钥
        glmClient = GLMClient("test-api-key")
    }

    @Test
    fun `test chat with valid message returns success`() = runTest {
        val result = glmClient.chat("你好")

        assertTrue(result.isSuccess)
        assertFalse(result.getOrNull().isNullOrEmpty())
    }

    @Test
    fun `test chat with empty message handles gracefully`() = runTest {
        val result = glmClient.chat("")

        assertTrue(result.isSuccess)
    }
}
3.2 Android集成测试步骤
  1. 配置API密钥 - 在应用中正确设置你的GLM API密钥
  2. 测试基础对话 - 输入简单问题,验证GLM-4.7响应
  3. 测试长对话 - 发送长文本,验证完整响应
  4. 测试异常情况 - 断开网络、错误API密钥等
  5. 性能测试 - 监控Android网络请求响应时间和内存使用

Android集成GLM-4.7踩坑记录

                            Android集成GLM-4.7常见坑

┌─────────────────────────────────────────────────────────────────────────────┐
│ 坑1: NetworkSecurityException                                              │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│   现象: Trust anchor for certification path not found                    │
│   原因: Android 9.0+默认不允许HTTP明文流量                               │
│   解决: 配置network_security_config.xml                                   │
│                                                                           │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│ 坑2: NetworkOnMainThreadException                                         │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│   现象: android.os.NetworkOnMainThreadException                           │
│   原因: 主线程直接发起网络请求                                             │
│   解决: 使用Kotlin协程(viewModelScope.launch)                             │
│                                                                           │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│ 坑3: API密钥硬编码                                                        │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│   现象: API密钥直接写在代码中                                             │
│   原因: 开发时为了方便                                                   │
│   解决: 使用local.properties或Android Keystore加密存储                     │
│                                                                           │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│ 坑4: JSON解析失败                                                         │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│   现象: JsonSyntaxException: Expected BEGIN_ARRAY but was BEGIN_OBJECT   │
│   原因: API响应格式与数据模型不匹配                                       │
│   解决: 使用@SerializedName处理字段名不一致                                 │
│                                                                           │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│ 坑5: 超时问题                                                             │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                           │
│   现象: API请求经常超时                                                   │
│   原因: 超时时间设置太短或服务器响应慢                                      │
│   解决: 增加OkHttp超时时间(60s) + 启用重试                               │
│                                                                           │
└─────────────────────────────────────────────────────────────────────────────┘

坑1: NetworkSecurityException错误

现象:

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

原因:
Android 9.0+默认不允许HTTP明文流量,而你的GLM-4.7 API使用的是HTTP而不是HTTPS。

解决方案:

  1. 优先使用HTTPS的API端点
  2. 如果必须使用HTTP,创建network_security_config.xml并配置
  3. <application>标签中引用配置:
    android:networkSecurityConfig="@xml/network_security_config"
    

坑2: NetworkOnMainThreadException

现象:

android.os.NetworkOnMainThreadException

原因:
在Android主线程直接发起了GLM-4.7 API网络请求,Android不允许这样做。

解决方案:
使用Kotlin协程或RxJava处理Android异步网络请求:

// ❌ 错误做法 - Android主线程网络请求
val response = apiService.chatCompletion(...)

// ✅ 正确做法 - 使用Kotlin协程处理异步
viewModelScope.launch {
    val response = apiService.chatCompletion(...)  // 在IO线程
}

坑3: API密钥硬编码问题

现象:
GLM-4.7 API密钥直接写在代码中,容易被泄露。

原因:
开发时为了方便直接将密钥写在代码中。

解决方案:

  1. 使用local.properties(不提交到Git):
    val apiKey = BuildConfig.API_KEY
    
  2. 或使用Android Keystore加密存储:
    val masterKey = MasterKey.Builder(applicationContext)
        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
        .build()
    
    val sharedPreferences = EncryptedSharedPreferences.create(
        applicationContext,
        "secret_shared_prefs",
        masterKey,
        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
    )
    

坑4: JSON解析失败

现象:

com.google.gson.JsonSyntaxException: Expected BEGIN_ARRAY but was BEGIN_OBJECT

原因:
GLM-4.7 API响应格式与定义的数据模型不匹配。

解决方案:

  1. 先查看原始API响应:
    Log.d("API", "Raw response: ${response.body()}")
    
  2. 根据实际响应调整数据模型
  3. 使用@SerializedName处理字段名不一致:
    data class GLMResponse(
        @SerializedName("choices") val choices: List<Choice>
    )
    

坑5: Android网络请求超时问题

现象:
GLM-4.7 API请求经常超时,用户体验差。

原因:
Android网络请求设置超时时间太短或服务器响应慢。

解决方案:

val okHttpClient = OkHttpClient.Builder()
    .connectTimeout(60, TimeUnit.SECONDS)  // 增加连接超时
    .readTimeout(60, TimeUnit.SECONDS)     // 增加读取超时
    .writeTimeout(60, TimeUnit.SECONDS)    // 增加写入超时
    .retryOnConnectionFailure(true)        // 启用重试
    .build()

Android集成GLM-4.7常见问题FAQ

Q1: 如何获取GLM-4.7的API密钥?

A: 访问智谱AI开放平台(https://open.bigmodel.cn/),注册账号后创建应用即可获取API密钥。新用户通常有免费额度。

Q2: Android支持GLM-4.7流式响应吗?

A: 支持,但需要额外处理。GLM-4.7支持SSE(Server-Sent Events)流式输出。你需要使用OkHttp的SSE库或WebSocket来接收流式数据。

Q3: Android如何处理GLM-4.7多轮对话上下文?

A: 将历史对话消息列表传递给GLM-4.7 API:

val messages = mutableListOf<Message>()
messages.add(Message(role = "user", content = "你好"))
messages.add(Message(role = "assistant", content = "你好!"))
messages.add(Message(role = "user", content = "刚才说的是什么?"))

glmClient.chat("", conversationHistory = messages)

Q4: GLM-4.7 token消耗如何计算?

A: GLM-4.7的token消耗包括输入token和输出token。可以通过响应中的usage字段查看:

val usage = response.usage
Log.d("Token", "Prompt: ${usage?.prompt_tokens}, " +
                 "Completion: ${usage?.completion_tokens}, " +
                 "Total: ${usage?.total_tokens}")

Q5: 如何优化GLM-4.7 API调用成本?

A:

  • 合理设置max_tokens参数,避免浪费
  • 使用缓存机制,避免重复请求相同内容
  • 对简单问题使用较小的模型
  • 实现本地缓存常用问答

Q6: GLM-4.7支持图片输入吗?

A: GLM-4.7目前主要支持文本,但GLM-4V等视觉模型支持图片输入。需要使用不同的API端点。

Q7: API调用返回404错误怎么办?

A: 检查以下几点:

  1. Base URL:确认是否为 https://open.bigmodel.cn/api/
  2. API路径:确认是否为 v4/chat/completions
  3. 旧版API:如果使用旧版,可能是 /paas/v4/chat/completions
  4. 官方文档:访问 https://open.bigmodel.cn/dev/api 确认最新API路径

Q8: 为什么默认max_tokens改为1024而不是2000?

A: 原因如下:

  1. 避免限流:过高token数可能触发API限流(429错误)
  2. 响应速度:较小的max_tokens响应更快
  3. 用户体验:对于大多数对话场景,1024 tokens已足够
  4. 按需调整:开发者可以根据实际需求调整此参数

Q9: temperature参数范围为什么是0-2?

A: GLM-4.7官方文档规定的温度范围是0-2:

  • 0-0.3:确定性输出,适合代码生成、逻辑推理
  • 0.3-0.7:平衡输出,适合对话、问答(推荐默认0.7)
  • 0.7-1.3:创造性输出,适合写作、头脑风暴
  • 1.3-2.0:高度随机,仅适用于特殊场景

其他模型(如GPT-4)可能使用0-1的范围,但GLM-4.7使用0-2。

延伸阅读

相关阅读


总结

通过这篇文章,你已经学会了:

  1. ✅ 在Android应用中集成GLM-4.7 API
  2. ✅ 处理Android网络权限和异步请求
  3. ✅ 使用Kotlin协程和Retrofit构建完整的对话界面
  4. ✅ 解决Android集成GLM-4.7时的常见问题

完整代码已经为你准备好了,可以直接复制到项目中使用。记得将API密钥换成你自己的。

如果遇到其他问题,欢迎在评论区讨论交流!


更多Android AI集成技巧: 加入知识星球,获取完整项目源码和更多GLM-4.7实战案例

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐