Не удается получить PDF-файл как двоичные данные - PullRequest
7 голосов
/ 10 марта 2011

Я пытаюсь получить файл PDF с:

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

, где он не указывает на прямой PDF-файл, и каждый уникальный файл загружается в интерпретацииконкретное поле <_id>.

Я помещаю эту ссылку в адресную строку браузера, и файл PDF загружается мгновенно, а когда я пытаюсь получить его по HTTPsURLConnection, его Content-Type находится в 'text / html'формы, в то время как это должно быть в «application / pdf».

Я также пытался установить «setRequestProperty» в «application / pdf» перед подключением, но файл всегда загружался в виде «text / html».

Метод, который я использую для этого, 'GET'

1) Нужно ли использовать HttpClient вместо HttpsURLConnection?

2) Используются ли эти типы ссылок дляповысить безопасность?

3) Пожалуйста, укажите мои ошибки.

4) Как узнать имя файла, присутствующее на сервере?

Я вставляю ниже основные коды, которыеЯ реализовал:

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

Я много искал и не смог получить результат.Если возможно, попробуйте уточнить мою ошибку, так как я впервые ее реализую.

** Попробовал получить прямые ссылки в формате PDF, такие как: http://labs.google.com/papers/bigtable-osdi06.pdf, и они легко загружаются, более того, их 'Content-Type 'также' application / pdf '**

Спасибо.

Ответы [ 2 ]

1 голос
/ 23 ноября 2012

Эта тема привела меня к решению моей проблемы!Когда вы пытаетесь загрузить потоковый PDF-файл из WebView и используете соединение HttpURLC, вам также необходимо передать куки из WebView.

String cookie = CookieManager.getInstance().getCookie(url.toString());
if (cookie != null) connection.setRequestProperty("cookie", cookie);
1 голос
/ 10 марта 2011

Теория 1. Сервер отвечает с неправильным типом содержимого в ответе. Если код сервера написан и развернут вами, проверьте это.

Теория 2: URL-адрес возвращает HTML-страницу, на которой есть некоторый JavaScript, который перенаправляет страницу на URL-адрес самого файла PDF.

...