【发布时间】: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