【发布时间】:2020-02-01 17:40:27
【问题描述】:
我想使用 google 函数从我的 Android 应用向 Google Firebase 发送请求。
因此,我在客户端定义了一个 API 接口,例如:
interface MyApi {
/**
* Get the list of the pots from the API
*/
@GET("/posts")
fun getPosts(): Observable<List<Post>>
@POST("/addUser")
fun addUser(@Query("name") name: String, @Query("token") token: String): Observable<User>
}
在 ModelView 中,我使用 RXJava 发送请求,例如:
subscription = Observable.fromCallable{ loveDateApi.addUser(name, token) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe( { result -> println("Result: $result") },
{error -> println("Error: $error")})
我观察到的用户对象如下所示:
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.gson.annotations.Expose
@Entity
data class User(
@Expose
@field:PrimaryKey
val idUser: Int,
@Expose
val token: String,
@Expose
val name: String,
@Expose
val age: Int
)
我提供改造的网络模块如下所示(只是摘录):
´´´
@Provides
@Reusable
@JvmStatic
internal fun provideRetrofitInterface(): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
.build()
}
´´´
在服务器端,我部署的谷歌云功能如下:
exports.addUser = functions.https.onRequest(async (request:any,response:any) => {
// read parameters from request
const name = request.query.name
const token = request.query.token
const data = {
name: name,
age: 30,
token: token
}
// use add if no doc-ID is specified else use set
const idUser = (await db.collection(collectionUser).add(data)).id
const newData = {
idUser: idUser,
}
const userRef = db.collection(collectionUser).doc(idUser)
await userRef.update(newData)
const newUserRef = await userRef.get()
response.send(newUserRef.data())
})
使用邮递员向云功能发送请求有效,但不幸的是在客户端应用程序中无效。
有什么想法吗?
【问题讨论】:
标签: android kotlin google-cloud-functions retrofit