如何在Parse查询中包含超时?

我的问题是关于Android的parse.com查询以及如果查询花费太长时间来响应,如何设置超时。

例如,我有一个查询,我从parse.com获取字符串列表。 如果此查询从parse.com收到的时间太长(例如,十秒),我希望用户能够取消查询(例如,使用屏幕弹出窗口)。 相反,应用程序在等待30秒后崩溃。

那么,有没有办法为查询设置自己的超时,然后适当地处理它们?

Https是与解析连接的协议。

Http(s) 允许完全控制以下内容:

套接字超时

getConnection超时

connectionRequest超时

为了操纵标题,我知道使用parse.com你可以使用Rest API,然后用你在构建器中的标题做任何你想要的事情….

public void create(int method, final String url, final String data) { this.method = method; this.url = url; this.data = data; if(method == GET){ this.config = RequestConfig.custom() .setConnectTimeout(6 * 1000) .setConnectionRequestTimeout(30 * 1000) .setSocketTimeout(30 * 1000) .build(); } else{ this.config = RequestConfig.custom() .setConnectTimeout(6 * 1000) .setConnectionRequestTimeout(30 * 1000) .setSocketTimeout(60 * 1000) .build(); } this.context = HttpClientContext.create(); 

如果你只使用android sdk,那么你需要在parse.com上的文档来弄清楚如何(或者是否可能)设置上面列出的http连接配置。

我的解决方案是使用RxJava Observable.timer(long delay,java.util.concurrent.TimeUnit unit)方法。

我声明了一个RxJava Subscription字段,然后在任何Parse.InBackground()代码之前将其初始化为Observable.timer(20,TimeUnit.SECONDS)调用。

在Observable.timer()方法中,我调用另一个方法,它将在try {…}块中抛出Javaexception,然后在下面的catch {…}块中处理抛出的exception。 这样做是让Observable.timer()调用在设置时间(例如上例中的20秒)耗尽后立即调用exception抛出方法。 通过在catch {…}块中处理它,您可以显示一个对话框/警报,通知用户操作已超时。

这是一个显示以下内容的代码段:

 Subscription timeoutWatcher; public void loginWithEmailAndPassword(@NonNull String email, @NonNull String password) { timeoutWatcher = Observable.timer(10, TimeUnit.SECONDS).subscribe(aLong -> { // Login timed out. Notify user to check Internet connection is chooppy. throwNetworkException("Timeout! Your Internet connection is unstable and preventing your sign in from completing on time. Please try again."); }); ParseUser.logInInBackground(email, password, (user, e) -> { // if Parse operation completes before timeout, then unsubscribe from the Observable.timer() operation timeoutWatcher.unsubscribe(); if (user != null) { // Hooray! The user is logged in. } else { // Signup failed. Look at the ParseException to see what happened. } }); } } private void throwNetworkException(String exceptionMessage) { try { throw new NetworkErrorException(exceptionMessage); } catch (NetworkErrorException e) { // show alert dialog } } 

不是最新的代码,但它适用于我。

不幸的是,没有办法为Parse请求指定超时。

相反,您可以捕获超时exception并采取必要的操作

 try{ ... }catch (ParseException e) { String mesg = e.getMessage(); if(mesg!= null && mesg.contains("java.net.SocketTimeoutException")){ // Do something here... } } 

注意 :如果使用inBackground Parse方法,则需要在回调方法中检查exception。