2012-03-08 78 views
1

我試圖創建一個應用程序,即使在網絡關閉時也能夠正常工作。 這個想法是將從RequestFactory返回的數據存儲在localStorage上,並在網絡不可用時使用localStorage。 我的問題 - 我不確定如何區分服務器錯誤(5XX,4XX,...)和網絡錯誤。 (我認爲在這兩種情況下我Receiver.onFailure()將被調用,但我還是不知道如何識別這種情況)RequestFactory和脫機客戶端

任何幫助,將不勝感激,

感謝, 吉拉德。

回答

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)); 
     } 
     } 

    }; 
    } 
相關問題