我从服务器下载文件。但是当我想要获得文件的大小总是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();
}
答案 0 :(得分:0)
HttpURLConnection connection = (HttpURLConnection) new URL(path).openConnection();
connection.setRequestProperty("Accept-Encoding", "identity");
long fileSize = connection.getContentLength();
用这种方式无论你下载文件的方式总是可以得到这样的大小。