1.5分钟后,改造OkHttp连接失败

时间:2017-05-23 06:06:00

标签: android retrofit2 okhttp3

我在后台以START_STICKY运行服务,获取用户位置并将其发送到我的服务器。

问题是当应用程序关闭时,服务运行良好。但是在1.5分钟后我得到java.net.ConnectException: Failed to connect to /10.0.0.14:2525没有原因,我无法察觉它为什么会发生。

我在Xiaomi Redme Not2上运行它并打开所有安全保障

对不起,这是一个很长的问题。但是我试着调试所有类,并且不知道出了什么问题。没有任何对象是Null或类似的东西

这是我的日志:

java.net.ConnectException: Failed to connect to /10.0.0.14:2525
at okhttp3.internal.io.RealConnection.connectSocket(RealConnection.java:139)
at okhttp3.internal.io.RealConnection.connect(RealConnection.java:108)
at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:188)
at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:127)
at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:273)
at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:215)
at okhttp3.RealCall.getResponse(RealCall.java:241)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:199)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:203)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:188)
at **com.smartbus.backend.RestProvider.lambda$buildClient$1(RestProvider.java:84)**
at com.smartbus.backend.RestProvider$$Lambda$2.intercept(Unknown Source)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:188)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:161)
at okhttp3.RealCall.execute(RealCall.java:57)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:118)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:86)
at **com.smartbus.utils.network.SynchronousRetrofitCall.execute(SynchronousRetrofitCall.java:27)
at com.smartbus.utils.tasks.PrepareRestApiTask.doInBackground(PrepareRestApiTask.java:43)
at com.smartbus.utils.tasks.PrepareRestApiTask.doInBackground(PrepareRestApiTask.java:24)**
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)

com.smartbus.utils.network.SynchronousRetrofitCall.execute(SynchronousRetrofitCall.java:27)

中会抛出异常

这是相关的课程

@AllArgsConstructor
public class SynchronousRetrofitCall<T> {

private final Call<T> mServiceCall;

public Optional<Response<T>> execute() {
    try {
        return Optional.of(mServiceCall.execute());
    } catch (IOException|JsonSyntaxException e) {
        e.printStackTrace();

        return Optional.absent();
    }
}

}

其他相关课程分为com.smartbus.backend.RestProvider.lambda$buildClient$1(RestProvider.java:84)com.smartbus.utils.tasks.PrepareRestApiTask.doInBackground(PrepareRestApiTask.java:43) com.smartbus.utils.tasks.PrepareRestApiTask.doInBackground(PrepareRestApiTask.java:24)

这是RestProvider类

public class RestProvider {

public static String CSRF_TOKEN = null;

private static OkHttpClient.Builder httpClientBuilder = new   OkHttpClient.Builder();
private static OkHttpClient client = null;
private static OkHttpClient clientWithAuth = null;

private static Retrofit.Builder builder = new  Retrofit.Builder().baseUrl(Consts.SERVER_URL)
  .addConverterFactory(GsonConverterFactory.create());

/* --- General methods --- */

/**
 * Method to reset the cookies for the provider
 */
public static void resetCookies() {
client = buildClient().build();
}

/**
* Method to build the HTTP Client
*/
private static OkHttpClient.Builder buildClient() {
httpClientBuilder = new OkHttpClient.Builder();
httpClientBuilder.cache(new Cache(getCacheDirectory(), 1024 * 1024 * 10));
httpClientBuilder.connectTimeout(30, TimeUnit.SECONDS); // connection
httpClientBuilder.readTimeout(30, TimeUnit.SECONDS);   // reading from the socket

httpClientBuilder.sslSocketFactory(getSslTrustingAll());
httpClientBuilder.hostnameVerifier((hostname, sslSession) -> {
  return Consts.SERVER_URL.contains(hostname);
});

httpClientBuilder.addInterceptor(chain -> {
  Request original = chain.request();

  Request.Builder requestBuilder = original.newBuilder()
      //.header("Authorization", basic)
      .addHeader("Accept", "applicaton/json")
      //.addHeader("Cache-Control", String.format("max-age=%d, only-    if-cached, max-stale=%d", 120, 0))
      .method(original.method(), original.body());

  if (CSRF_TOKEN != null) {
    requestBuilder.addHeader("X-CSRFToken", CSRF_TOKEN);
    requestBuilder.addHeader("Referer", Consts.SERVER_URL);
  }

  Request request = requestBuilder.build();
  return chain.proceed(request);///// !!!!the relevant line is here!!!/////
});

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();

logging.setLevel(HttpLoggingInterceptor.Level.BODY);

//httpClientBuilder.addInterceptor(new GzipRequestInterceptor());
httpClientBuilder.addInterceptor(logging);

httpClientBuilder.cookieJar(new SmartCookieJar());
return httpClientBuilder;
}

 public static <S> S createService(Class<S> serviceClass) {

if (client == null) {
  client = buildClient().build();
}

Retrofit retrofit = builder.client(client).build();

return retrofit.create(serviceClass);
}

这是PrepareRestApiTask类:

@SuppressWarnings("Guava")
@RequiredArgsConstructor
public class PrepareRestApiTask<responseObject> extends AsyncTask<Void, Void, Optional<Response<RestResponse<responseObject>>>> {
private static final String TAG = "restApi";

private final restApiCaller<responseObject> caller;

public static Optional<String> connectToRestServer() {
    return Optional.fromNullable(LocalStore.getToken());
}

@Override
protected Optional<Response<RestResponse<responseObject>>> doInBackground(Void... voids) {
    Optional<String> hashedToken = connectToRestServer();
    if (!hashedToken.isPresent()) {
        cancel(false);
        return null;
    }
    SmartbusClient client =   RestProvider.createService(SmartbusClient.class);
/////!!!this is the relevant line!!!//////
    return new SynchronousRetrofitCall<>(caller.onRestApiReadyBackgroundRun(hashedToken.get(), client)).execute();
}

@Override
protected void onPostExecute(Optional<Response<RestResponse<responseObject>>> responseOptional) {
    if (!responseOptional.isPresent()) {
        return;
    }
    if (responseOptional.get().isSuccess() && responseOptional.get().body().isOk())
        caller.onEverythingFinishedUIThreadRun(responseOptional.get().body().data);
    else {
        if (responseOptional.get().isSuccess()) {
            Log.e(TAG, "error connecting to restApi: " + responseOptional.get().body().error);
        } else {
            try {
                Log.e(TAG, "error connecting to restApi: " + responseOptional.get().errorBody().string());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        caller.onError(responseOptional.get());
    }
}

@Override
protected void onCancelled(Optional<Response<RestResponse<responseObject>>> responseOptional) {

}

@Override
protected void onCancelled() {
    onCancelled(null);
}

public interface restApiCaller<responseObject> {
    Call<RestResponse<responseObject>> onRestApiReadyBackgroundRun(String hashedToken, SmartbusClient client);

    void onEverythingFinishedUIThreadRun(responseObject theData);

    void onError(Response<RestResponse<responseObject>> response);
}
}

这就是服务:

public class GpsService extends Service
implements GoogleApiClient.ConnectionCallbacks,   GoogleApiClient.OnConnectionFailedListener,
LocationListener {

public static final String TAG_PRIORITY = "priority";
public static final int PRIORITY_LISTEN_ONLY = 1;
public static final int PRIORITY_PERFECT = 2;


public static final int PRIORITY_BALANCED = 3;
  public static final String TAG_STOP_ON_FIRST_LOCATION = "stop_first_location";
  public static final String TAG_RETURN_TO_LISTEN_MODE = "return_to_listen_mode";
  private static final String TAG = "GpsService";
  private static final long INTERVAL_TIME_LISTEN_MS = 1000 * 60 * 10;
  private static final long INTERVAL_TIME_BALANCED_MS = 1000 * 30;
  private static final long INTERVAL_TIME_PERFECT_MS = 1000 * 5;
  private static final float ACCURACY_METERS = 60f;
  public static final int REQUEST_CHECK_SETTINGS = 4359;
  private static LogUtils logUtils = new LogUtils(TAG);
  private CalendarRide currentRide;
  private int timeToResetGps = 1000 * 60 * 30;

  static {
    logUtils.setActive(false);
  }

  private GoogleApiClient mGoogleApiClient;
  //    @Getter private static GpsService instance = null;
  private int priority;
  private boolean shouldStop = false;
  String mUsername;
  int mDeviceId;
  Date lastTalkToServer;
  static List<GpsCallback> callbacks = new ArrayList<>();

  public GpsService() {
    super();
    logUtils.logFunctionCalled();
  }

  @Nullable @Override public IBinder onBind(Intent intent) {
    logUtils.logFunctionCalled();
    return null;
  }

  @Override public void onCreate() {
    super.onCreate();
    logUtils.logFunctionCalled();
    lastTalkToServer = new Date(0);

    mUsername = LocalStore.getUsername();
    if (mUsername == null) {
      try {
        mUsername = User.getCurrentUser().username;
      } catch (NullPointerException e) {
        stopSelf();
      }
    }
    mDeviceId = FirebasePhoneIdService.getDeviceId();

    //        instance = this;
    mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .addApi(LocationServices.API)
        .build();
    if (LocalStore.getToken() == null) stopSelf();

    logUtils.logFunctionOut();
  }

  @Override public int onStartCommand(Intent intent, int flags, int startId) {
    logUtils.logFunctionCalled();
    priority = intent.getIntExtra(TAG_PRIORITY, PRIORITY_LISTEN_ONLY);
    shouldStop = intent.getBooleanExtra(TAG_STOP_ON_FIRST_LOCATION, false);
    logUtils.custom(
        "priority: " + priority + " PRIORITY_LISTEN: " + LocationRequest.PRIORITY_NO_POWER);

    if (mGoogleApiClient.isConnected()) {
      disconnectLocations();
    }
    mGoogleApiClient.connect();
    logUtils.logFunctionOut();
    return START_STICKY;
  }

  @Override public void onConnected(@Nullable Bundle bundle) {
    logUtils.logFunctionCalled();

    LocationRequest req = LocationRequest.create();
    req.setFastestInterval(0);
    req.setSmallestDisplacement(0f);
    switch (priority) {
      case PRIORITY_BALANCED:
        req.setInterval(INTERVAL_TIME_BALANCED_MS);
        req.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        break;
      case PRIORITY_PERFECT:
        req.setInterval(INTERVAL_TIME_PERFECT_MS);
        req.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        break;
      case PRIORITY_LISTEN_ONLY:
      default:
        req.setInterval(INTERVAL_TIME_LISTEN_MS);
        req.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }
    checkIfRequestIsValidAndStartGps(req);


  }

  @Override public void onConnectionSuspended(int i) {
    Log.e(TAG, "google connection suspended");
  }

  @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.d(TAG, "google connection failed");
    mGoogleApiClient.disconnect();
    mGoogleApiClient.connect();
  }
  @Override public void onLocationChanged(Location location) {
    //        logUtils.custom("onLocationChanged: " + location.getLongitude()+"---"+location.getLatitude()+"    accuracy:"+location.getAccuracy());
    //if (location.hasAccuracy() && location.getAccuracy() <= ACCURACY_METERS) {
      // found a good location
      onGoodLocationFound(location);
    currentRide = CalendarRide.getCurrentRideForGps();
    if (currentRide != null){
      checkIfNeedToReturnGpsToListenMode();
    }
    //}
//    float[] distance = new float[1];
//    Location.distanceBetween(location.getLatitude(), location.getLongitude(), 31.7568686, 35.2016888,distance);
//    float resultse = distance[0];
  }

  private void checkIfNeedToReturnGpsToListenMode() {
    Date now = Calendar.getInstance().getTime();
    Date rideEndTime = currentRide.getEndTime();
    if (now.getTime() - rideEndTime.getTime() >= timeToResetGps ){
      CalendarRide.setCurrentRideForGps(null);
      LocationRequest req = LocationRequest.create();
      req.setInterval(INTERVAL_TIME_LISTEN_MS);
      req.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
      checkIfRequestIsValidAndStartGps(req);
    }

}

private void onGoodLocationFound(Location location) {
tellTheServer(location);
if (shouldStop) {
  restartSilentMode();
}
for (Iterator<GpsCallback> callbackIterator = callbacks.iterator();
    callbackIterator.hasNext(); ) {
  GpsCallback callback = callbackIterator.next();
  boolean shouldContinue = callback.onGoodLocationFound(location);
  if (!shouldContinue) callbackIterator.remove();
}
}
.....
private void tellTheServer(Location location) {
if (talkedToServerRecently()) return;
logUtils.custom("starting communication with server");
if (mDeviceId == -1) { // can't update the server
  mDeviceId =
      LocalStore.getDeviceId(); // better luck next time (meanwhile maybe the user has connected)
  return;
}

new PrepareRestApiTask<>(new PrepareRestApiTask.restApiCaller<String>() {
  @Override public Call<RestResponse<String>> onRestApiReadyBackgroundRun(String hashedToken,
      SmartbusClient client) {
    DriverPlaceUpdate newPlace =
        new DriverPlaceUpdate(location.getLatitude(), location.getLongitude(), location.getSpeed()*3.6);
    return client.update_driver_location(newPlace, hashedToken);
//        return client.update_driver_location(mUsername, mDeviceId, newPlace, hashedToken);
  }

  @Override public void onEverythingFinishedUIThreadRun(String theData) {
    Log.d(TAG, "server response went well");
    lastTalkToServer = new Date();
  }

  @Override public void onError(Response<RestResponse<String>> response) {
    if (response == null) return;
    mDeviceId =
        LocalStore.getDeviceId(); // if the problem is that there is no device, initTask it

    try {
      Log.e(TAG, response.errorBody().string());
    } catch (IOException e) {
      e.printStackTrace();
      try {
        Log.e(TAG, response.body().error);
      } catch (NullPointerException ignore) {
      }
    }
  }
}).execute();
}

由于

0 个答案:

没有答案