【问题标题】:android content Length() return -1android内容长度()返回-1
【发布时间】:2018-03-07 09:25:09
【问题描述】:

我从服务器下载文件。但是当我想获取文件大小时,总是 body.contentLength() 返回 -1 。有一些方法可以用HttpUrlConnection 解决这个问题,但是ResponseBody 类呢?

  private void initDownload(){

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://mobleh.com/").build();    
        RequestInterface requestInterface = retrofit.create(RequestInterface.class);    
        Call<ResponseBody> request = requestInterface.getAPK(path);

        try {    
            downloadFile(request.execute().body());

        } catch (IOException e) {

            e.printStackTrace();
            Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();

        }
    }

    private void downloadFile(ResponseBody body) throws IOException {

        int count;
        byte data[] = new byte[1024 * 4];            
        long fileSize = body.contentLength();

}

【问题讨论】:

    标签: android android-studio retrofit2 content-length http-content-length


    【解决方案1】:

    经过一些研究和思考,我做了一些技巧,只需像这样使用 HttpURLConnection 获取文件大小:

    HttpURLConnection connection = (HttpURLConnection) new URL(path).openConnection();
    
        connection.setRequestProperty("Accept-Encoding", "identity");
    
    long fileSize = connection.getContentLength();
    

    这种方式不管你用哪种方式下载文件,总能得到这样的大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-09
      • 2014-07-13
      • 2012-06-23
      • 2013-09-14
      • 2011-11-17
      • 1970-01-01
      • 2011-06-08
      • 1970-01-01
      相关资源
      最近更新 更多