Web API调用抛出错误java.net.SocketTimeoutException

时间:2018-06-13 11:24:12

标签: android kotlin rx-java2 mvp rx-android

我有一个我在Kotlin + MVP architecture开发的Android项目。它在项目中总共有30个API调用,但有时会从任何一个API中随机抛出套接字超时错误。我不知道在服务器或API或Kotlin-MVP或Rx2AndroidNetworking中是否存在问题?

下面我将向您展示在Kotlin + MVP中调用产品列表Web API调用。

我在iOS中开发的这个项目并没有抛出这个错误,所以它在服务器或API开发上没有错误。我认为这个问题发生在Rx2AndroidNetworking库中。

过去有没有人有任何想法或遇到过这个问题?

enter image description here

java.net.SocketTimeoutException

failed to connect to / (port 80) after 120000ms: isConnected failed: ETIMEDOUT (Connection timed out)
   at libcore.io.IoBridge.isConnected(IoBridge.java:232)
   at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
   at libcore.io.IoBridge.connect(IoBridge.java:122)
   at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
   at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
   at java.net.Socket.connect(Socket.java:884)
   at okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.java:70)
   at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:238)
   at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:158)
   at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:256)
   at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:134)
   at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:113)
   at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
   at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
   at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
   at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:125)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
   at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
   at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
   at okhttp3.RealCall.execute(RealCall.java:77)
   at com.rx2androidnetworking.Rx2InternalNetworking$SimpleANObservable.subscribeActual(Rx2InternalNetworking.java:187)
   at io.reactivex.Observable.subscribe(Observable.java:10981)
   at io.reactivex.internal.operators.observable.ObservableDoOnEach.subscribeActual(ObservableDoOnEach.java:42)
   at io.reactivex.Observable.subscribe(Observable.java:10981)
   at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
   at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
   at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
   at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
   at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:154)
   at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:269)
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
   at java.lang.Thread.run(Thread.java:818)

ProductInteractor.kt

class ProductInteractor @Inject internal constructor(apiHelper: ApiHelper, preferenceHelper: PreferenceHelper) : BaseInteractor(apiHelper = apiHelper, preferenceHelper = preferenceHelper), ProductMVPInteractor {

override fun getProductList(pagingAndSortingInfo: PagingAndSortingInfo?, searchBy: String, categoryIds: String) =
        apiHelper.performProductListApiCall(pagingAndSortingInfo, searchBy, categoryIds)
}

ProductPresenter.kt(it.showError(t!!.message!!)行抛出套接字超时Toast消息)

class ProductPresenter<V : ProductGridMVPView, I : ProductMVPInteractor> @Inject internal constructor(interator: I, schedulerProvider: SchedulerProvider, compositeDisposable: CompositeDisposable) : BasePresenter<V, I>(interactor = interator, schedulerProvider = schedulerProvider, compositeDisposable = compositeDisposable), ProductMVPPresenter<V, I> {
override fun onViewPrepared(pageNumber: Long?, categoryIds: String?) {

    getView()?.showProgress()
    interactor?.let {
        val pagingAndSortingInfo = PagingAndSortingInfo(AppConstants.PAGE_SIZE.toLong(),
                pageNumber,
                0,
                true,
                true,
                "DisplayOrder",
                AppConstants.SortDirection.Ascending.type)
        var disposable = it.getProductList(pagingAndSortingInfo, "", categoryIds.toString())
                .compose(schedulerProvider.ioToMainObservableScheduler())
                .subscribe ({ productResponse ->
                    getView()?.let {
                        it.hideProgress();
                        var totalRecords: Long? = 0;
                        var currentPage: Long? = 0;
                        var isPagingRequired: Boolean? = false;
                        totalRecords = productResponse.pagingAndSortingInfo!!.totalRecord;
                        currentPage = productResponse.pagingAndSortingInfo!!.pageNumber;
                        isPagingRequired = productResponse.pagingAndSortingInfo!!.isPagingRequired;
                        it.displayProductList(productResponse.productItems, totalRecords, currentPage, isPagingRequired);
                    }
                },{
                    t: Throwable? ->  getView()?.let {
                    it.hideProgress()
                    it.showError(t!!.message!!)
                }
                })
        addSubscription(disposable)
    }
}
}

ProductGridFragment.kt(我在我的产品片段onViewCreated中调用presenter类如下所示。)

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    presenter.onAttach(this)
    super.onViewCreated(view, savedInstanceState)

    srl_product.setOnRefreshListener(object : SwipeRefreshLayout.OnRefreshListener {

        override fun onRefresh() {
            productAdapter.clearData()
            setPageNumber(1);
            setCategoryIds("");
            presenter.onViewPrepared(getPageNumber(), getCategoryIds());
            srl_product.isRefreshing = false;
        }

    })
}

performProductListApiCall Function(在Interactor类中调用此函数)

override fun performProductListApiCall(request: PagingAndSortingInfo?, searchBy: String?, categoryIds: String?): Observable<ProductResponse> =
        Rx2AndroidNetworking.post(ApiEndPoint.ENDPOINT_PRODUCT_GETLIST)
                .addHeaders("Authorization", "bearer " + prefHelper.getAccessToken())
                .addQueryParameter("searchBy", searchBy)
                .addQueryParameter("categoryIds", categoryIds)
                .addBodyParameter(request)
                .setOkHttpClient(okHttpClient)
                .build()
                .getObjectObservable(ProductResponse::class.java)
                .doOnError {
                    t: Throwable -> Log.e("performProductListApiCall", t.message);
                }

1 个答案:

答案 0 :(得分:0)

  

之前:

.setOkHttpClient(okHttpClient)

  

添加以下行:

OkHttpClient okHttpClient= new OkHttpClient();
client.setConnectTimeout(15, TimeUnit.MINUTES); // connect timeout
client.setReadTimeout(15, TimeUnit.MINUTES);    // socket timeout