改进Observables并获得响应(Retrofit Observables and access to Response)

编程入门 行业动态 更新时间:2024-10-26 07:25:20
改进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(); } }

更多推荐

本文发布于:2023-08-06 11:14:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1448640.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Retrofit   Observables   Response   access

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!