我正在使用Android上的Firebase Cloud Functions库,并使用getHttpsCallable
来调用云函数。
问题在于该函数需要10到15秒才能将结果返回给客户端,因此客户端会引发异常java.net.SocketTimeoutException: timeout
。
代码
// Create the arguments to the callable function.
Map<String, Object> data = new HashMap<>();
data.put("info", info);
mFunctions.getHttpsCallable(function)
.call(data)
.continueWith(new Continuation<HttpsCallableResult, String>() {
@Override
public String then(@NonNull Task<HttpsCallableResult> task) {
// This continuation runs on either success or failure, but if the task
// has failed then getResult() will throw an Exception which will be
// propagated down.
if (task.isSuccessful()) {
String result = (String) task.getResult().getData();
Log.v(Constants.LOG_TAG, result);
return result;
} else {
// The condition never was true, always logs the exception.
Exception e = task.getException();
Log.e(Constants.LOG_TAG, "Failed to join multiplayer room.", e);
return null;
}
}
});
如何更改超时,以便客户端在引发异常之前等待更多时间?
注意。我没有使用OkHttp,Retrofit或默认的系统网络功能,而是使用Firebase Cloud Functions库(getHttpsCallable
)来调用该函数。
答案 0 :(得分:1)
firebase-functions
版本16.3.0 released 15 Mar 2019向configure the timeout添加了功能。
答案 1 :(得分:0)
我遇到了同样的问题,所以我使用OkHttp而不是getHttpsCallable来调用https函数作为解决方法。
https.onCall的协议是公共的。
https://firebase.google.com/docs/functions/callable
使用OkHttp调用https函数的代码在这里。
https://github.com/ryuta46/firebase-callable-okhttp/blob/56adc5e29a35bdb3b355c14d734e6145da4b6809/android/app/src/main/java/com/ttechsoft/okhttp_callable/MainActivity.kt#L184-L239
已编辑。
重要部分的代码如下。
private fun callWithOkHttp(functionName: String) {
val idToken = idToken ?: return
val instanceId = instanceId ?: return
val projectId = FirebaseApp.getInstance()?.options?.projectId ?: return
val url = "https://us-central1-$projectId.cloudfunctions.net/$functionName"
val jsonData = JSONObject()
jsonData.put("text", "inputText")
val json = JSONObject()
json.put("data", jsonData)
val requestBody = RequestBody.create(JSON, json.toString())
val request = Request.Builder()
.url(url)
.post(requestBody)
.addHeader("Authorization", "Bearer $idToken")
.addHeader("Firebase-Instance-ID-Token", instanceId)
.build()
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(1 , TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES)
.build()
Log.i(TAG, "Start Okhttp")
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful) {
val message = response.body()?.string() ?: "Network Error"
runOnUiThread {
textOkHttpResult.text = message
}
return
}
runOnUiThread {
textOkHttpResult.text = "OK"
}
val responseBody = response.body()
Log.i(TAG, responseBody?.string())
}
override fun onFailure(call: Call, e: IOException) {
val message = e.message ?: "Unknown Network error"
runOnUiThread {
textOkHttpResult.text = message
}
}
})
}