RequestFactory and offline clients

早过忘川 提交于 2019-12-08 07:35:22

问题


I'm trying to create an application which is able to work even when network is down. The idea is to store data returned from RequestFactory on the localStorage, and to use localStorage when network isn't available. My problem - I'm not sure exactly how to differentiate between server errors(5XX, 4XX, ...) and network errors. (I assume that on both cases my Receiver.onFailure() would be called, but I still don't know how to identify this situation)

Any help would be appreciated,

Thanks, Gilad.


回答1:


The response code when there is no internet connection is 0.

With RequestFactory to identify that the request was unsuccessful because of the network the response code has to be accessed. The RequestTransport seems like the best place.

Here is a rough implementation of an 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));
        }
      }

    };
  }


来源:https://stackoverflow.com/questions/9616611/requestfactory-and-offline-clients

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!