RequestFactory和离线客户端

时间:2012-03-08 11:02:11

标签: gwt requestfactory

我正在尝试创建一个即使在网络中断时也能工作的应用程序。 我们的想法是将从RequestFactory返回的数据存储在localStorage上,并在网络不可用时使用localStorage。 我的问题 - 我不确定如何区分服务器错误(5XX,4XX,...)和网络错误。 (我假设在两种情况下都会调用我的Receiver.onFailure(),但我仍然不知道如何识别这种情况)

任何帮助将不胜感激,

谢谢, 吉拉德。

1 个答案:

答案 0 :(得分:1)

没有互联网连接时的响应代码为0.

使用RequestFactory来识别请求因网络而失败,必须访问响应代码。 RequestTransport似乎是最好的地方。

以下是OfflineAwareRequestTransport的粗略实现。

   public class OfflineAwareRequestTransport extends DefaultRequestTransport {

  private final EventBus eventBus;
  private boolean online = true;

  public OfflineAwareRequestTransport(EventBus eventBus) {
    this.eventBus = eventBus;
  }

  @Override
  public void send(final String payload, final TransportReceiver receiver) {

    // super.send(payload, proxy);
    RequestBuilder builder = createRequestBuilder();
    configureRequestBuilder(builder);

    builder.setRequestData(payload);
    builder.setCallback(createRequestCallback(receiver, payload));
    try {
      builder.send();
    } catch (RequestException e) {
    }
  }

  protected static final int SC_OFFLINE = 0;

  protected RequestCallback createRequestCallback(final TransportReceiver receiver,
      final String payload) {

    return new RequestCallback() {

      public void onError(Request request, Throwable exception) {
        receiver.onTransportFailure(new ServerFailure(exception.getMessage()));
      }

      public void onResponseReceived(Request request, Response response) {
        if (Response.SC_OK == response.getStatusCode()) {
          String text = response.getText();
          setOnline(true);
          receiver.onTransportSuccess(text);
        } else if (response.getStatusCode() == SC_OFFLINE) {
          setOnline(false);
          boolean processedOk = processPayload(payload);
          receiver.onTransportFailure(new ServerFailure("You are offline!", OfflineReceiver.name,
              "", !processedOk));
        } else {
          setOnline(true);
          String message = "Server Error " + response.getStatusCode() + " " + response.getText();
          receiver.onTransportFailure(new ServerFailure(message));
        }
      }

    };
  }