Rxjava - UndeliverableException

时间:2018-04-09 12:47:12

标签: android rx-android

我使用响应式android来处理我的后端请求,问题是请求有时有效,有时不行。 我得到了例外

io.reactivex.exceptions.UndeliverableException: android.os.NetworkOnMainThreadException

在Mainactivity onCreate()中我调用发送帖子请求的GetServices函数

获取服务

public Observable<Response> GetService() {

        return Observable.fromCallable(new Callable<Response>() {
            @Override
            public Response call() throws Exception {
                return RequestHelper.GetRequest("getvendoractiveservices");
            }
        });

    }


    public void GetServices()
    {
        GetService().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Response>() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

            }

            @Override
            public void onNext(@io.reactivex.annotations.NonNull Response value) {
                try {
                    Log.w("services",value.body().string()); //exception here
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {

            }
        });
    }

我的后请求

public static String URI="http://192.168.137.1:4000/";
    public static Response PostRequest(String api, FormBody formBody)
    {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(URI+api)
                .header("carmen-token", LoginActivity.token)
                .post(formBody)
                .build();

        try {
            return client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

0 个答案:

没有答案