Java Android:从http获取文件并存储在SD卡中

Java Android:从http获取文件并存储在SD卡中,java,android,jsp,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

我已经关注了许多类似问题中的内容,但仍然存在一个问题

从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中,我在异步任务中执行以下操作:

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();
你知道当它试图获取二进制pdf文件时为什么不工作吗

失败在哪里


感谢您的专业知识…

这对我很有用。请尝试修改以下内容:

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);
在清单文件中添加此行:


是的,已测试且存在相同的问题,如果我在while中放入一个日志,写入len1,它只有2个字节,while没有更多的迭代(下一个tiem len1==-1)。我尝试过的每件事都应该是有效的,但有些地方我错过了,奇怪的。。。(仅更改注释行连接。addRequestProperty(BConstant.WEB\u SERVICES\u COOKIES,cookie))使用我的代码您只需更改url和fname。fname可以是文件的任何字符串名称。它会像黄油一样起作用。只需尝试硬编码url,然后运行代码。您的代码在java应用程序中工作,但在应用程序中不工作,尝试使用harcoded字符串也会出现相同的错误,但发现了问题,代码正常(您的代码和我的前一个代码),因此问题在于通信,因为url已从外部服务器重定向到内部服务器,似乎有一些问题在那里或在服务器,将检查,代码正在工作,谢谢。啊,我不能投票给你的答案好,因为我没有声誉,但谢谢!!!
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" />