如何修复连接超时

时间:2019-09-01 13:46:00

标签: java android retrofit

我的连接超时:

2019-09-01 18:20:52.732 9389-9389/com.example.homecinema E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.homecinema, PID: 9389
io.reactivex.exceptions.OnErrorNotImplementedException: connect timed out
    at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704)
    at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701)
    at io.reactivex.internal.observers.LambdaObserver.onError(LambdaObserver.java:77)
    at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.checkTerminated(ObservableObserveOn.java:276)
    at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.drainNormal(ObservableObserveOn.java:172)
    at io.reactivex.internal.operators.observable.ObservableObserveOn$ObserveOnObserver.run(ObservableObserveOn.java:252)
    at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:109)
    at...

代码概述如下

public void loginUser(String email, String password) {
    compositeDisposable.add(myAPI.loginUser(email,password)
        .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Consumer<String>() {
                @Override
                public void accept(String s) throws Exception {
                    if(s.contains("encrypted_password")){
                        Toast.makeText(getApplicationContext(), "login 
                        Successful" , LENGTH_SHORT).show();
                    }
                    else {
                        Toast.makeText(getApplicationContext(),""+s, 
                          LENGTH_SHORT).show();
                    }
                }
            })
    );

1 个答案:

答案 0 :(得分:0)

通过Retrotit Builder使用自定义Http客户端,如下所示:

public class RetrofitConfig {

    public Retrofit getConfig(){
        return new Retrofit.Builder().client(httpClient())
            .baseUrl(ApiDomain.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    }
    private OkHttpClient httpClient() {
        return new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();
    }
}

这将管理您的改造超时。当然,请确保在超时之前得到响应,否则您也需要处理重试。