繁体   English   中英

android内容长度()返回-1

[英]android content Length() return -1

我从服务器下载文件。 但是当我想获取文件大小时,总是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();

}

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

HttpURLConnection connection = (HttpURLConnection) new URL(path).openConnection();

    connection.setRequestProperty("Accept-Encoding", "identity");

long fileSize = connection.getContentLength();

用这种方式下载文件的方式无关紧要,总是可以获得这样的大小。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM