2011-03-10 18 views
7

Estoy tratando de obtener un archivo PDF a partir de:Es imposible acceder al archivo PDF como datos binarios

URL: https://domain_name/xyz/_id/download/

en la que no apunta a un archivo PDF directa y cada archivo único se descarga interpretando un campo particular < _id>.

pongo este enlace en la barra de direcciones del navegador de archivos PDF y se descarga al instante, mientras que cuando trato de buscarla por HttpsURLConnection su Content-Type está en '/ html texto' forma, mientras que debería ser en 'application/pdf'.

También traté de 'setRequestProperty' a 'application/pdf' antes de conectar, pero el archivo siempre se descarga en 'text/html'.

método que estoy usando para ello es 'GET'

1) ¿Es necesario utilizar HttpClient en lugar de HttpsURLConnection?

2) ¿Se utilizan estos tipos de enlaces para aumentar la seguridad?

3) Señale mis errores.

4) ¿Cómo puedo saber el nombre del archivo presente en el servidor?

estoy pegando a continuación los códigos principales que he implementado:

URL url = new URL(sb.toString()); 

    //created new connection 
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); 

    //have set the request method and property 
    urlConnection.setRequestMethod("GET"); 
    urlConnection.setDoOutput(true); 
    urlConnection.setRequestProperty("Content-Type", "application/pdf"); 

    Log.e("Content Type--->", urlConnection.getContentType()+" "+ urlConnection.getResponseCode()+" "+ urlConnection.getResponseMessage()+"    "+urlConnection.getHeaderField("Content-Type")); 

    //and connecting! 
    urlConnection.connect(); 

    //setting the path where we want to save the file 
    //in this case, going to save it on the root directory of the 
    //sd card. 
    File SDCardRoot = Environment.getExternalStorageDirectory(); 

    //created a new file, specifying the path, and the filename 

    File file = new File(SDCardRoot,"example.pdf"); 

    if((Environment.getExternalStorageState()).equals(Environment.MEDIA_MOUNTED_READ_ONLY)) 

    //writing the downloaded data into the file we created 
    FileOutputStream fileOutput = new FileOutputStream(file); 

    //this will be used in reading the data from the internet 
    InputStream inputStream = urlConnection.getInputStream(); 

    //this is the total size of the file 
    int totalSize = urlConnection.getContentLength(); 

    //variable to store total downloaded bytes 
    Log.e("Total File Size ---->", ""+totalSize); 
    int downloadedSize = 0; 

    //create a buffer... 
    byte[] buffer = new byte[1024]; 
    int bufferLength = 0; //used to store a temporary size of the buffer 

    //Reading through the input buffer and write the contents to the file 
    while ((bufferLength = inputStream.read(buffer)) > 0) { 

     //add the data in the buffer to the file in the file output stream (the file on the sd card 
     fileOutput.write(buffer, 0, bufferLength); 


     //adding up the size 
     downloadedSize += bufferLength; 

     //reporting the progress: 
     Log.e("This much downloaded---->",""+ downloadedSize); 

    } 
    //closed the output stream 
    fileOutput.close(); 

He buscado mucho y no pude conseguir el resultado. Si es posible, por favor intente elaborar mi error ya que estoy implementando esta cosa por primera vez.

** Intentamos ir a buscar enlaces directos como pdf: http://labs.google.com/papers/bigtable-osdi06.pdf y que se descargan fácilmente, por otra parte su 'Content-Type' también fue 'application/pdf' **

Gracias.

+0

¿Ha comprobado el tipo MIME con el que responde el servidor? –

Respuesta

1

¡Este hilo me llevó a la solución de mi problema! Cuando intenta descargar un archivo PDF en tiempo real desde la WebView y utiliza una HttpURLConnection, también debe pasar las cookies desde Webview.

String cookie = CookieManager.getInstance().getCookie(url.toString()); 
if (cookie != null) connection.setRequestProperty("cookie", cookie); 
1

Teoría 1: El servidor está respondiendo con un tipo de contenido incorrecto en respuesta. Si el código del servidor está escrito e implementado por usted, verifique eso.

Teoría 2: La URL está devolviendo una página html que tiene algunos javascript que redirigen la página a la url del archivo pdf real.

+0

La URL que intento abrir tiene una representación de pdf en línea en la que muestra archivos pdf incrustados en la página web. ¿Crees que esto puede ser un problema? Porque, cuando uso el navegador Firefox, lo renderizo dentro de WebPage, pero cuando abro este enlace en el navegador Chrome, descarga el archivo. Entonces, ¿hay algo que pueda hacer para obtener directamente el pdf como binario en lugar de recibir 'html/text' o las modificaciones deben hacerse en el lado del servidor. No he implementado el código del servidor. – iabhi

+0

@ al-sutton @nishan He comprobado a través de FireBug que lo muestra como objeto de aplicación/pdf. Entonces, ¿necesito hacer algún cambio para acceder al pdf incrustado en una página web? – iabhi

+0

Además, puedo descargar el tamaño exacto del archivo del pdf pero en 'text/html', en lugar de recibirlo como 'application/pdf', así que muestra "No se pudo abrir el tipo de archivo de texto/html" – iabhi

Cuestiones relacionadas