【问题标题】:Android Retrofit Download/Reading Text File From ServerAndroid Retrofit 从服务器下载/读取文本文件
【发布时间】:2016-05-28 21:56:11
【问题描述】:

如何使用 Retrofit 甚至更好的 Rx Retrofit 下载和读取文本文件?

以下是改造时间之前的示例。 真的是如何在 Retrofit 中转换下面的代码 示例:

try {
    // Create a URL for the desired page
    URL url = new URL("ksite.com/thefile.txt");

    // Read all the text returned by the server
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String str;
    while ((str = in.readLine()) != null) {
        // str is one line of text; readLine() strips the newline character(s)
    }
    in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

非常感谢您的帮助。谢谢

【问题讨论】:

    标签: java android http retrofit rx-java


    【解决方案1】:

    编辑: 从 Retrofit 1.6 版本开始有一个 @Streaming 注释,可用于提供原始 InputStream。可用于下载文件。

    IMO Retrofit 不是下载文件的最佳工具(除非文件包含 JSON)。

    使用 Retrofit(第 2 版)意味着您在后台使用 OkHttp。 OkHttp 是更好的文件下载工具。

    使用 OkHttp 的异步获取如下所示:

    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());
          }
        });
      }
    

    更多内容请关注recipes section on Github

    也来自维基:

    响应体上的 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()

    【讨论】:

    • 谢谢,我需要将正文作为流处理。会试试的
    • 是否有机会使用 AndroidRx 改进此代码?谢谢
    猜你喜欢
    • 2018-11-13
    • 1970-01-01
    • 2020-11-04
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    相关资源
    最近更新 更多