du8828
du8828
2017-05-18 11:52

来自PHP服务器的Android下载文件

已采纳

I am trying to download a file from my PHP server. Here is my PHP code:

$file = 'androidApps/app.apk';

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);

exit;

File name and file size are correct. When I use my browser (on my computer AND on my phone) everything is fine. The file is correctly downloaded.

When I try to download it from my android app it will download a 38-byte file. Still in my android app if I use the direct link to my file it will download it correctly. Here is my android code:

    String path ="http://myserverURLAndPhpFileUrl.php";//If I put the path of my file it will download it correctly
    String PATH = Environment.getExternalStorageDirectory() + "/download/";
    URL u = null;

    u = new URL(path);
    HttpURLConnection c = (HttpURLConnection) u.openConnection();
    c.setRequestMethod("GET");
    c.connect();

    InputStream in = c.getInputStream();

    File file = new File(PATH);
    file.mkdirs();
    File outputFile = new File(file, "app.apk");
    FileOutputStream fos = new FileOutputStream(outputFile);
    InputStream is = c.getInputStream();

    byte[] buffer = new byte[1024];
    int len1 = 0;
    while ((len1 = is.read(buffer)) != -1) {
        fos.write(buffer, 0, len1);
        System.out.println(len1);
    }
    fos.close();
    is.close();`

I have also tried to use the DownloadManager but I get the same issue:

  String path = "http://myserverURLAndPhpFileUrl.php";
   UpdateService.this.getSystemService(UpdateService.this.DOWNLOAD_SERVICE);
    DownloadManager.Request dlrequest = new DownloadManager.Request(Uri.parse(path));

    dlrequest.setVisibleInDownloadsUi(true);


dlrequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
    dlrequest.setDestinationInExternalFilesDir(UpdateService.this, null, "app.apk");
    System.out.println("FILE dir: " + getExternalFilesDir(null));
    //nqueue this request e
    DownloadManager downloadManager = (DownloadManager) UpdateService.this.getSystemService(UpdateService.this.DOWNLOAD_SERVICE);
    long downloadID = downloadManager.enqueue(dlrequest);
    downloadManager.enqueue(dlrequest);

I am using this code in a service. I have tested on android 5.0.1 and Android 4.3

PHP version: 5.4.45-0+deb7u8

How can I manage to download my file without using the path of the file ?

Thanks

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dspows0637 dspows0637 4年前

    My code is fine. I just had to add cookies in my request:

     dlrequest.addRequestHeader("Cookie","PHPSESSID="+session);
    
    点赞 评论 复制链接分享

为你推荐