Kotlin Jetpack Compose无端点POST请求FormData失效问题求助
解决Retrofit无端点POST请求FormData传递失败问题
问题根源
你用@Multipart标记接口会让Retrofit发送multipart/form-data类型请求,但多数通过action参数区分接口的后端服务,实际期望接收的是application/x-www-form-urlencoded类型的普通表单数据,这是请求失败的核心原因。
修正方案
将@Multipart替换为@FormUrlEncoded,同时把@Part注解改为@Field,具体修改如下:
修改后的ApiInterface
interface ApiInterface { @FormUrlEncoded @POST("/") suspend fun getRendomFact( @Field("secret_key") secretKey: String, @Field("token") token: String, @Field("action") action: String ): Response<HomeData> }
其他代码无需改动
你的Base URL定义、Retrofit实例初始化以及请求调用逻辑保持原样即可。
额外优化建议
- 避免使用
GlobalScope,在Activity中改用lifecycleScope(ViewModel中用viewModelScope),协程会自动跟随生命周期管理,避免内存泄漏:
// MainActivity中替换GlobalScope为lifecycleScope fun sendResponse() { lifecycleScope.launch(Dispatchers.IO) { // 原有请求逻辑不变 } }
- 可添加OkHttp日志拦截器,查看实际发送的请求头和参数,方便排查问题:
// RetrofitInstance中添加日志拦截器 val api : ApiInterface by lazy { val logging = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } val client = OkHttpClient.Builder() .addInterceptor(logging) .build() Retrofit.Builder() .baseUrl(Util.Base) .client(client) .addConverterFactory(GsonConverterFactory.create()) .build() .create(ApiInterface::class.java) }
添加日志拦截器需在build.gradle引入依赖:
implementation "com.squareup.okhttp3:logging-interceptor:4.12.0"
内容的提问来源于stack exchange,提问作者Arvind Gehlod
相关产品推荐
相关产品推荐

