Я пытаюсь получить файл PDF по адресу:
URL: https: // имя_домена / xyz / _id / download /
, где он не ' t указывает на прямой файл 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» **
Спасибо.