简体   繁体   中英

Corrupted APK when downloading in Java but browser download works fine

I am trying to download an APK hosted in a server. When downloading via browser, it works fine. I get 14MB. But when downloading using Java, the APK seems corrupted since APK downloaded is just aroung 189kb. Below is my code when downloading using Apache Commons FileUtils:

URL format is similar to https://example.com/emm.apk . Entering this URL in a browser directly downloads the APK without problem.

    URL url = new URL("https://example.com/emm.apk");
    File file = new File(UUID.randomUUID().toString() +"-"+ FilenameUtils.getName(fileUrl.getPath()));
    FileUtils.copyURLToFile(url, file, 50_000, 50_000);

I also tried Java's built in File IO:

    URLConnection conn = url.openConnection();
    int contentLength = conn.getContentLength();

    DataInputStream stream = new DataInputStream(url.openStream());

    byte[] buffer = new byte[contentLength];
    stream.readFully(buffer);
    stream.close();

    DataOutputStream fos = new DataOutputStream(new FileOutputStream(file));
    fos.write(buffer);
    fos.flush();
    fos.close();

I only get this problem for that particular URL. I cannot pinpoint what's wrong since I don't have access with the host server. Clearly the problem is with how the APK is hosted. Is there requirements on how servers hosting APK should be configured? I came across application/vnd.android.package-archive , is this required for host servers? Why does the browser (Chrome) downloads it without problem while my Java code does not?

It seems that host server of the APK is blocking requests based on the User-Agent request header that's why browser download is okay but when downloading in different medium, it's not.

I tried manually setting the User-Agent of the URLConnection , and it's downloading properly.

URLConnection connection = fileUrl.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
InputStream input = connection.getInputStream();
FileUtils.copyInputStreamToFile(input, file);

The 189kb is an HTML file saying the request was rejected.

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