【问题标题】:Android download file from PHP server从 PHP 服务器下载 Android 文件
【发布时间】:2017-10-18 05:21:33
【问题描述】:

我正在尝试从我的 PHP 服务器下载一个文件。这是我的 PHP 代码:

$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;

文件名和文件大小正确。 当我使用浏览器(在我的电脑和手机上)时,一切都很好。文件已正确下载。

当我尝试从我的 android 应用程序下载它时,它会下载一个 38 字节的文件。 如果我使用指向我的文件的直接链接,它仍然在我的 android 应用程序中,它将正确下载。 这是我的安卓代码:

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

我也尝试过使用 DownloadManager,但遇到了同样的问题:

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

我在服务中使用此代码。 我已经在 android 5.0.1 和 Android 4.3 上测试过

PHP版本:5.4.45-0+deb7u8

如何在不使用文件路径的情况下下载文件?

谢谢

【问题讨论】:

  • 您使用了错误的网址。里面没有主机。
  • final ByteArrayOutputStream bo = new ByteArrayOutputStream();。删除该行。它令人困惑。
  • 使用完整的 url 到你的 php 脚本。
  • 我没有在 stackoverflow 上写完整的网址,但我在我的应用程序中使用了正确的网址
  • 您可以发布比现在更好的假网址。你知道它现在是多么令人困惑。

标签: php android


【解决方案1】:

我的代码很好。我只需要在我的请求中添加 cookie:

 dlrequest.addRequestHeader("Cookie","PHPSESSID="+session);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 2012-10-13
    相关资源
    最近更新 更多