Android:从http获取文件并存储在SDCard中

时间:2014-01-22 10:09:12

标签: java android jsp

我已经按照许多类似问题所写的内容,但仍有问题

从jsp我得到一个pdf,如果我转到URL,浏览器自动打开pdf,jsp页面就像这样:

//Gets the pdf from the database
BufferedInputStream bis = new BufferedInputStream(file.getBinaryStream(), buffer);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int readed=0;
while ((readed=bis.read())!=-1) baos.write(readed);
bis.close();
byte[] pdf=baos.toByteArray();
response.setContentType("application/pdf");
response.setContentLength(pdf.length);              
response.getOutputStream().write(pdf, 0, pdf.length);

此代码有效,因为如果我们浏览到URL,我们会将PDF放入浏览器中。

然后在Android中我在AsyncTask中执行:

InputStream is = null;
try {
URL url = new URL(myurl); // <-- this is the same URL tested into browser
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
FileOutputStream fos = new FileOutputStream(getWorkingDir()+fileName);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength(); //<- this seems to be incorrect,     totalSize value is 22 but file is more than 50Kb length
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
while ( (bufferLength = inputStream.read(buffer)) >=0) {
  fos.write(buffer, 0, bufferLength);
  downloadedSize += bufferLength;
  // at this point downloadedSize is only 2, and next iteration in while exists so a file os size 2bytes is created...
}
fos.close();

当然我有权使用SD编写并在AndrodiManifest.xml中使用Internet

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我直接尝试了URLConnection,得到了InputStream,我们得到了相同的结果,只读了2个字节......

如果我尝试将string.getBytes()写入已写入的文件,则写入外部文件正在运行。

如果我们得到conn.getResponseCode()它是200,那么没关系。

根据参数,相同的.jsp可以返回一个文档列表(以JSON格式)或PDF格式,如果我们提供他的数据库ID,如果我们得到pdf列表,它可以工作,在这种情况下,它会像:

reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
    stringBuilder.append(line); 
}

当它试图获取二进制pdf文件时,知道为什么不工作?

失败在哪里?

感谢您的专家......

1 个答案:

答案 0 :(得分:2)

它为我工作尝试修改它:

private void savePrivateExternalFile(String fileURL, String fName) {
   HttpURLConnection connection = null;
    URL url = null;
    try {

        url = new URL(fileURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.addRequestProperty(BConstant.WEB_SERVICES_COOKIES,
                cookie);
             connection.setDoOutput(true);
        connection.connect();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    File folderDir = null;
        folderDir = new File(getExternalFilesDir("Directory Name") + "/Files");

    File file = new File(folderDir, fName);

    if (file.exists()) {
        file.delete();
    }

    if ((folderDir.mkdirs() || folderDir.isDirectory())) {
        try {
            InputStream inputStream = connection.getInputStream();
            BufferedInputStream bufferedInputStream = null;

                bufferedInputStream = new BufferedInputStream(inputStream,
                        1024 * 5);

            FileOutputStream fileOutputStream = new FileOutputStream(
                    folderDir + "/" + fName);
            byte[] buffer = new byte[1024];
                int len1 = 0;
                while ((len1 = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, len1);
                }

                bufferedInputStream.close();

            fileOutputStream.close();
            inputStream.close();
            connection.disconnect();
            } catch (Exception e) {
            e.printStackTrace();
        }
      }

如果要打开已下载的文件,请使用此选项:

File file = new File(getExternalFilesDir("Directory Name")+ "/Files/" + fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);

在您的清单文件中添加以下行:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />