Retrofit 2.0 - How to get response body for 400 Bad Request error?

前端 未结 9 1878
旧巷少年郎
旧巷少年郎 2021-01-31 02:33

So when I make a POST API call to my server, I get a 400 Bad Request error with JSON response.

{
    \"userMessage\": \"Blah\",
    \"internalMessage\": \"Bad Re         


        
9条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-31 03:03

    I got similar issue, but existing code was stick to RxJava 2 chain. Here's my solution:

       public static  Observable rxified(final Call request, final Class klazz) {
        return Observable.create(new ObservableOnSubscribe() {
    
            AtomicBoolean justDisposed = new AtomicBoolean(false);
    
            @Override
            public void subscribe(final ObservableEmitter emitter) throws Exception {
    
                emitter.setDisposable(new Disposable() {
                    @Override
                    public void dispose() {
                        request.cancel();
                        justDisposed.set(true);
                    }
    
                    @Override
                    public boolean isDisposed() {
                        return justDisposed.get();
                    }
                });
    
                if (!emitter.isDisposed())
                    request.enqueue(new Callback() {
                        @Override
                        public void onResponse(Call call, retrofit2.Response response) {
                            if (!emitter.isDisposed()) {
                                if (response.isSuccessful()) {
                                    emitter.onNext(response.body());
                                    emitter.onComplete();
    
                                } else {
                                    Gson gson = new Gson();
                                    try {
                                        T errorResponse = gson.fromJson(response.errorBody().string(), klazz);
                                        emitter.onNext(errorResponse);
                                        emitter.onComplete();
                                    } catch (IOException e) {
                                        emitter.onError(e);
                                    }
                                }
                            }
                        }
    
                        @Override
                        public void onFailure(Call call, Throwable t) {
                            if (!emitter.isDisposed()) emitter.onError(t);
                        }
                    });
            }
        });
    }
    

    transforming 400-like responses into rx chain is pretty simple:

    Call request = catApi.getCat();
    rxified(request, Cat.class).subscribe( (cat) -> println(cat) );
    

提交回复
热议问题