編輯: 有因爲版本@Streaming
註釋改造1.6,可用於輸送原料InputStream
。可用於下載文件。
IMO改造是不是下載文件(除非該文件包含JSON)的最佳工具。
使用改造(版本2)意味着使用的是OkHttp引擎蓋下。 OkHttp是下載文件的更好工具。
與OkHttp異步得到如下:
在
recipes section on Github
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Request request, IOException throwable) {
throwable.printStackTrace();
}
@Override public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
});
}
更多。
同樣來自維基:
上響應身體的串()方法是方便和有效的用於 小的文件。但是,如果響應正文很大(大於1 MiB),請避免使用string(),因爲它會將整個文檔加載到 內存中。在這種情況下,更願意將流體作爲流處理。
編輯: 使用RxJava
public interface Api {
@Streaming
@GET("path to file")
Observable<ResponseBody> getFile();
}
api.getFile()
.flatMap(responseBody -> {
try {
return Observable.just(responseBody.string());
} catch (IOException e) {
return Observable.error(e);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(System.out::println);
同樣,你可能不應該使用responseBody.string()
更大的文件。
謝謝,我需要處理的身體流。試試吧 – Joolah
任何機會都可以用AndroidRx改進這段代碼?謝謝 – Joolah