2015-07-22 34 views
0

我使用改造庫。如果我失去了互聯網連接,我有錯誤。但我有問題。如果我關掉wifi並在一段時間後發送請求到服務器,我有錯誤。但是,如果我立即發送請求,我有超時但互聯網禁用。我認爲這是因爲互聯網立即關閉。是否有可能立即確定互聯網已經消失?確定缺乏互聯網(改造)

現在我用這個

public final class SkipUrlConnectionClient extends UrlConnectionClient { 
     @Override 
     protected HttpURLConnection openConnection(Request request) throws IOException { 
      HttpURLConnection connection = super.openConnection(request); 
      connection.setConnectTimeout(5 * 60 * 1000); 
      connection.setReadTimeout(5 * 60 * 1000); 
      return connection; 
     } 
    } 


private RestAdapter.Builder getBuilder(RequestInterceptor requestInterceptor) { 
     RestAdapter.Builder builder = new RestAdapter.Builder() 
       .setEndpoint(BuildConfig.ROOT_URL_SKIP) 
       .setClient(new SkipUrlConnectionClient()) 
       .setRequestInterceptor(requestInterceptor) 
       .setConverter(new JacksonConverter()); 
     builder.setLogLevel(RestAdapter.LogLevel.FULL); 
     return builder; 
    } 
+0

改造回調有onFailure處你在哪裏得到[改裝錯誤](http://square.github.io/retrofit/javadoc/retrofit/RetrofitError.html)。用它來確定它是什麼類型的錯誤。 –

+0

是的,我知道。有用。但是如果我關閉了Internet,並且在超時被觸發後發送請求 – ip696

回答

0

您可以檢查您的網絡連接的狀態,在執行使用ConnectivityManager請求之前。看看這個guide

0

添加到Mimmo的答案。

定義一個自定義的Interceptor類來實現攔截(Chain chain)方法。你會檢查那裏的連通性。如果沒有連接,拋出你自己的Exception類。

樣品在這裏:http://www.migapro.com/detect-offline-error-in-retrofit-2/

public class ConnectivityInterceptor implements Interceptor { 

    private Context mContext; 

    public ConnectivityInterceptor(Context context) { 
     mContext = context; 
    } 

    @Override 
    public Response intercept(Chain chain) throws IOException { 
     if (!NetworkUtil.isOnline(mContext)) { 
      throw new NoConnectivityException(); 
     } 

     Request.Builder builder = chain.request().newBuilder(); 
     return chain.proceed(builder.build()); 
    } 

}