我的问题是,我不确定如何使用androidannotation rest api来下载文件,以下是我的示例代码。
我已经创建了一个restful服务,如下所示:
@Controller
@RequestMapping("/")
public class BaseController {
private String filePath = "web-inf/scheduler/downloadList.properties";
private static final int BUFFER_SIZE = 4096;
@RequestMapping(value = "/files", method = RequestMethod.GET)
public void getLogFile(HttpServletRequest request, HttpServletResponse response) throws Exception{
// get absolute path of the application
ServletContext context = request.getSession().getServletContext();
String appPath = context.getRealPath("");
System.out.println("appPath = " + appPath);
// construct the complete absolute path of the file
String fullPath = appPath + filePath;
File downloadFile = new File(fullPath);
FileInputStream inputStream = new FileInputStream(downloadFile);
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
downloadFile.getName());
response.setHeader(headerKey, headerValue);
// get output stream of the response
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
// write bytes read from the input stream into the output stream
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
}如果我使用谷歌浏览器浏览网址"http://[hostname]:8080/mnc-sms-endpoint/files“,那么它就能够下载文件。
现在,我想创建一个android应用程序来从这个restful服务中获取文件。
下面是我的android代码:但它总是给我显示错误,实际上我对androidannotation和spring-android还是个新手。
@Rest(converters = { ByteArrayHttpMessageConverter.class })
public interface MainRestClient extends RestClientHeaders {
// url variables are mapped to method parameter names.
@Get("http://192.168.1.37:8080/mnc-sms-endpoint/files")
@Accept(MediaType.APPLICATION_OCTET_STREAM)
byte[] getEvents();
}下面是我的android活动:
@EActivity(R.layout.activity_main)
public class MainActivity extends Activity {
@RestService
MainRestClient mainRestClient;
@AfterViews
protected void init() {
mainRestClient.getEvents();}
}发布于 2014-03-26 16:15:47
当您的应用程序调用WS时会出现什么错误?
此外,您还应该删除@Accept(...)注释,因为WS可能会返回与application/octet-stream不同的内容类型(因为String mimeType = context.getMimeType(fullPath);这一行)
https://stackoverflow.com/questions/22651700
复制相似问题