我正在尝试下载PDF文件,但看起来它只是在下载空白页。另外,当我查看我的文件文件夹并从中打开PDF时,仅显示空白页。我认为我的下载方式存在问题。这是我的DownloadService.class的一部分,也是我在api接口中的调用的一部分。
@Streaming
@GET()
Call<ResponseBody> downloadFileWithDynamicUrlAsync(@QueryMap(encoded = true) Map<String, String> options, @Query("id") int id);
public class DownloadService extends IntentService {
private void initDownload(){
Retrofit retrofit = APIClient.getClient();
APIInterface retrofitInterface = retrofit.create(APIInterface.class);
Map<String, String> parms = new HashMap<>();
parms.put("fn", "GetPDF");
Call<ResponseBody> request = retrofitInterface.downloadFileWithDynamicUrlAsync(parms, 33);
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();
InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "SAVEDPDFS");
folder.mkdir();
File outputFile = new File(folder, fileName);
OutputStream output = new FileOutputStream(outputFile);
long total = 0;
long startTime = System.currentTimeMillis();
int timeCount = 1;
while ((count = bis.read(data)) != -1) {
total += count;
totalFileSize = (int) (fileSize / (Math.pow(1024, 2)));
double current = Math.round(total / (Math.pow(1024, 2)));
int progress = (int) ((total * 100) / fileSize);
long currentTime = System.currentTimeMillis() - startTime;
Download download = new Download();
download.setTotalFileSize(totalFileSize);
if (currentTime > 1000 * timeCount) {
download.setCurrentFileSize((int) current);
download.setProgress(progress);
sendNotification(download);
timeCount++;
}
output.write(data, 0, count);
}
onDownloadComplete();
output.flush();
output.close();
bis.close();
}
}
这些是我在清单中设置的权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />