title: Download files with Android Webview
body: <p>I am making an Android app that uses a WebView to access to a webpage. To handle downloads I am using AsyncTask in method onDownloadStart of WebView's DownloadListener. However files downloaded are blank (although the filename and extension are correct). My Java code is this:</p>
  
  <pre><code>protected String doInBackground(String... url) {  
      try {
          URL url = new URL(url[0]);    
  
          //Creating directory if not exists
  
          HttpURLConnection connection = (HttpURLConnection) url.openConnection();
          connection.setRequestMethod("GET");
          connection.setDoOutput(true);        
          connection.connect();
  
          //Obtaining filename
  
          File outputFile = new File(directory, filename);
          InputStream input   = new BufferedInputStream(connection.getInputStream());
          OutputStream output = new FileOutputStream(outputFile);
  
          byte data[] = new byte[1024];
          int count = 0;
          Log.e(null, "input.read(data) = "+input.read(data), null);
          while ((count = input.read(data)) != -1) {
              output.write(data, 0, count);
          }              
          connection.disconnect();
          output.flush();
          output.close();
          input.close();
      } catch (MalformedURLException e) {
          e.printStackTrace();
      } catch (IOException e) {
           e.printStackTrace();
      }
      return null;
  }
  </code></pre>
  
  <p>log.e line gives -1 value for input.read(data).
  PHP code of download page is this (works in all platforms). Files are stored in non-public directories of my HTML server.</p>
  
  <pre><code>&lt;?php
  $guid = $_GET['id'];
  $file = get_file($guid);
  
  if (isset($file['path'])) { 
      $mime = $file['MIMEType'];
      if (!$mime) {
          $mime = "application/octet-stream";
      }
  
      header("Pragma: public");
      header("Content-type: $mime");
      header("Content-Disposition: attachment; filename=\"{$file['filename']}\"");
      header('Content-Transfer-Encoding: binary');
  
      ob_clean();
      flush();
      readfile($file['path']);
      exit();
  
  }
  ?&gt;
  </code></pre>
  
  <p>I've noticed that if I write some text after "?>" of PHP file, this text is written in the file downloaded.  </p>