简体   繁体   中英

android content Length() return -1

I download file from server. but when i want get size of file always body.contentLength() return -1 . some ways fix this issue with HttpUrlConnection but how about ResponseBody class ?

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

}

after some research and thinking i made some trick , just get size of file with HttpURLConnection like this :

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

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

long fileSize = connection.getContentLength();

with this way dos not matter which way you download files , always can get your size like this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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