改进Observables并获得响应(Retrofit Observables and access to Response)
我正在使用Retrofit和RxJava,但似乎无法做我想要的。
这是我对我的网络服务的声明:
Observable<Response> rawRemoteDownload(@Header("Cookie") String token, @Path("programId") int programId);我遇到的问题是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) { } });解:
感谢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())); } }convertToString的位置如下:
private String convertToString(TypedInput body) { byte[] bodyBytes = ((TypedByteArray) body).getBytes(); return new String(bodyBytes); }I'm using Retrofit and RxJava but can't seem to do what I want.
Here's my declaration of my web service:
Observable<Response> rawRemoteDownload(@Header("Cookie") String token, @Path("programId") int programId);The problem I have is the webservice is returning a 403 and a json payload with details.
Retrofit calls onError, only passing the Throwable so I can't check the response body.
Here's part of my test code
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) { } });SOLUTION:
Thanks to Gomino, I went with this as a solution:
new Action1<Throwable>() { @Override public void call(Throwable throwable) { if (throwable instanceof RetrofitError) { Response response = ((RetrofitError) throwable).getResponse(); System.out.println(convertToString(response.getBody())); } }where convertToString looks like:
private String convertToString(TypedInput body) { byte[] bodyBytes = ((TypedByteArray) body).getBytes(); return new String(bodyBytes); }最满意答案
检查throwable是否是RetrofitError:
@Override public void onError(Throwable e) { if (e instanceof RetrofitError) { Response response = ((RetrofitError) e).getResponse(); } }Check if the throwable is a RetrofitError:
@Override public void onError(Throwable e) { if (e instanceof RetrofitError) { Response response = ((RetrofitError) e).getResponse(); } }更多推荐
发布评论