改进Observables并获得响应

Fin*_*ive 4 rx-java retrofit

我正在使用Retrofit和RxJava,但似乎无法做我想要的.

这是我对我的网络服务的声明:

Observable<Response> rawRemoteDownload(@Header("Cookie") String token, @Path("programId") int programId);
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是webservice返回403和一个带有详细信息的json有效负载.

Retrofit调用onError,只传递Throwable,所以我无法检查响应体.

这是我的测试代码的一部分

apiManager.rawRemoteDownloadRequest("token", 1).subscribe(new Observer<Response>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            // this is called and I've lost the response!
        }

        @Override
        public void onNext(Response response) {

        }
    });
Run Code Online (Sandbox Code Playgroud)

解:

感谢Gomino,我将其作为解决方案:

new Action1<Throwable>() {
        @Override
        public void call(Throwable throwable) {
            if (throwable instanceof RetrofitError) {
                Response response = ((RetrofitError) throwable).getResponse();

                System.out.println(convertToString(response.getBody()));
            }
        }
Run Code Online (Sandbox Code Playgroud)

convertToString的位置如下:

private String convertToString(TypedInput body) {
    byte[] bodyBytes = ((TypedByteArray) body).getBytes();
    return new String(bodyBytes);
}
Run Code Online (Sandbox Code Playgroud)

Gom*_*ino 6

检查throwable是否是RetrofitError:

@Override
public void onError(Throwable e) {
   if (e instanceof RetrofitError) {
      Response response = ((RetrofitError) e).getResponse();
   }
}
Run Code Online (Sandbox Code Playgroud)