android-带改造2的流服务器-分块
作者:互联网
我应该从服务器返回一个带有Transfer-Encoding:块的json的流媒体终结点.
我有以下代码,但无法读取响应.我尝试了responseBody.streamBytes()并将输入流转换为String,但是在主线程中却做不到.我如何阅读回复?
@Streaming
@GET("stream/status")
Observable<ResponseBody> streamStatus();
Observable<ResponseBody> observable = ApiClientHelper.getClient().streamStatus();
observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(final ResponseBody responseBody) {
//DON'T KNOW HOW TO READ DATA
}
@Override
public void one rror(Throwable e) {
}
@Override
public void onComplete() {
}
});
编辑:
使用CURL的服务器响应:
* Trying 192.168.1.3...
* TCP_NODELAY set
* Connected to 192.168.1.3 (192.168.1.3) port 80 (#0)
> GET /stream/meter HTTP/1.1
> Host: 192.168.1.3
> User-Agent: curl/7.54.0
> Accept: */*
> Cookie:sessionId=bf2533346190e1c72b532b9d6ec6a405
>
< HTTP/1.1 200 OK
< Content-Type: text/event-stream
< Cache-Control: no-cache, no-store
< Date: Tue, 17 Oct 2017 12:02:03 GMT
< Transfer-Encoding: chunked
< Connection: Keep-Alive
<
data: {"production":{"ph-a":{"p":-0.817,"q":0.0,"s":47.302,"v":225.697,"i":0.21,"pf":0.0,"f":50.0},"ph-b":{"p":-0.066,"q":-0.0,"s":0.643,"v":3.091,"i":0.206,"pf":0.0,"f":50.0},"ph-c":{"p":-0.195,"q":-0.0,"s":0.943,"v":7.577,"i":0.123,"pf":0.0,"f":50.0}},"net-consumption":{"ph-a":{"p":-0.598,"q":0.0,"s":51.931,"v":225.606,"i":0.231,"pf":0.0,"f":50.0},"ph-b":{"p":-0.088,"q":0.0,"s":0.875,"v":4.585,"i":0.19,"pf":0.0,"f":50.0},"ph-c":{"p":-0.043,"q":0.0,"s":0.16,"v":1.23,"i":0.13,"pf":-1.0,"f":50.0}},"total-consumption":{"ph-a":{"p":-1.415,"q":-0.0,"s":-4.599,"v":225.652,"i":-0.02,"pf":-1.0,"f":50.0},"ph-b":{"p":-0.154,"q":0.0,"s":0.06,"v":3.838,"i":0.016,"pf":-1.0,"f":50.0},"ph-c":{"p":-0.237,"q":0.0,"s":-0.033,"v":4.404,"i":-0.008,"pf":-1.0,"f":50.0}}}
解决方法:
添加@Streaming批注会导致改型,而不是将整个文件移入内存,而是立即传入的字节.这使您能够处理可能大于可用总内存的数据流.但是,如果您尝试在主线程上执行此操作,则将获得android.os.NetworkOnMainThreadException,这是我认为您得到的.因此,问题出在.observeOn(AndroidSchedulers.mainThread)中.
编辑:
公平警告.我还没有运行.
observable
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable disposable) {
}
@Override
public void onNext(ResponseBody responseBody) {
InputStream inputStream = responseBody.byteStream();
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(inputStream));
while (br.ready()) {
line = br.readLine();
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Log.d("streamed string", sb.toString()); // replace log with whatever you want to do with it.
}
@Override
public void one rror(Throwable throwable) {
}
@Override
public void onComplete() {
}
});
标签:chunked,retrofit2,android 来源: https://codeday.me/bug/20191110/2015489.html