【问题标题】:How to parse fileinputstream returned from ResponceEntity.getbody() to write into a file in android如何解析从 ResponceEntity.getbody() 返回的文件输入流以写入 android 中的文件
【发布时间】:2016-04-01 13:18:04
【问题描述】:

我想从服务器下载文件(.docx、.pdf、图像或任何类型)。我正在使用 spring-mvc REST API。通过使用 Resttemplate.exchange(...) 我得到了来自服务器的响应流的形式,但我无法解析它。那么我应该如何做到这一点并写入文件?

文件返回码(服务器):

public ResponseEntity<?> downloadFile(..){
 if (downloadFile.exists()) {
      FileInputStream fileInputStream = new FileInputStream(downloadFile);
      return ResponseEntity.ok()
                          .contentLength(downloadFile.length())
                          .contentType(MediaType.parseMediaType("application/octet-stream"))
                          .body(newInputStreamResource(fileInputStream));}
 else {
        return responseEntity.status(HttpStatus.NOT_FOUND)
        .body(ErrorMsgWebapiUtil.AUTHORIZED_USER);
            }
                    }

来自服务器的响应:

����P����Â*����@8B����G¨������á���� ¡����#T����p ����P����Â*����@8B����G¨������á���� ¡����óÿ��0\§ÁzõK���� ����IEND®B`

在我的 Android(客户端)上编写代码:

 try {
        mRespEntity = mRestTemplate.exchange(strFinal, HttpMethod.POST, mRequestEntity, String.class);
        mResponseCode = mRespEntity.getStatusCode().toString();

        if (mResponseCode.equals("200")) {

            String outdir = "sdcard/downloads/";

            int length = Integer.parseInt(mRespEntity.getHeaders().getContentLength() + "");
            inputStream = new BufferedInputStream((InputStream) mRespEntity.getBody()); //Here it Throughs Exception:java.lang.String cannot be cast to java.io.InputStream
            byte[] buffer = new byte[length];
            int read = 0;

            File dFile = new File(outdir, filename);

             fos = new DataOutputStream(new FileOutputStream(dFile));

            while ((read = inputStream.read(buffer)) != -1) {
                fos.write(buffer, 0, read);
            }

        }
    } catch (Exception e) {
        if (e != null) {
            e.printStackTrace();
            Log.e(TAG, "getFileFolderSyncData() Error:" + e.getMessage());
            return false;
        }

    } finally {

        // resetSSLFactory();

        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (fos != null) {
            try {
                // outputStream.flush();
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

在 Line inputStream = new BufferedInputStream((InputStream) mRespEntity.getBody());这里通过异常:“java.lang.String 不能转换为 java.io.InputStream”

【问题讨论】:

  • mRespEntity.getBody() 正在返回字符串而不是 InputStream 所以只有你得到这个异常,ResponseEntity> 你把它作为通用的,你能检查一下这个 String bodyVal=mRespEntity.getBody() ;在你的代码中,让我们现在看看它是什么
  • 字符串 strBody=mRespEntity.getBody(); InputStream is = new ByteArrayInputStream(strBody.getBytes());inputStream = new BufferedInputStream(is );你可以试试这个可能有帮助
  • 感谢海军!但还有另一个问题。当我使用您建议的代码编写图像文件时,我无法打开它..打开图像文件时出错

标签: android spring-mvc resttemplate


【解决方案1】:

找到解决方案...

public String FileDownload(...){
     String url = ....;
            String res = ...;
            String outdir = ...;
            File outputFile = new File(outdir, filename);


            BufferedInputStream in = null;
            FileOutputStream fout = null;


            try {
                URL obj = new URL(url);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();

                con.setRequestMethod("POST");
                con.setRequestProperty("param1", value);//post parameters

                String urlParameters = ...;
                // Send post request
                con.setDoOutput(true);
                DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                wr.writeBytes(urlParameters);
                wr.flush();
                wr.close();

                int responseCode = con.getResponseCode();

                if (responseCode == 200) {
                    in = new BufferedInputStream(con.getInputStream());
                    fout = new FileOutputStream(outputFile);

                    final byte data[] = new byte[1024];
                    int count;
                    while ((count = in.read(data, 0, 1024)) != -1) {
                        fout.write(data, 0, count);
                    }
                    res = "true";
                } else {
                    res = con.getResponseMessage();
                }

            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "Exception in file Download:" + e.getMessage());
                res = "false";
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                    if (fout != null) {
                        fout.close();
                    }
                    res = "true";
                } catch (IOException e) {
                    e.printStackTrace();
                    res = "false";
                }
            }

            return res;
}

【讨论】:

  • 你能告诉我们是什么导致了这个问题吗?
猜你喜欢
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-25
  • 2022-01-12
  • 2012-06-13
相关资源
最近更新 更多