我正试图从以下地址获取一个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”。
谢谢。