1.我做的这个项目,后台下载总是报解析失败错误,或者下载百分比问题。
百分比问题是由于Content-Length不正确导致的,必须要求后台传正确的apk大小。
Controll 代码
@RequestMapping(value = "/downloadApp", method = RequestMethod.GET)
@ApiOperation(httpMethod = "GET", value = "下载文件", produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
@ResponseBody
public Object download(@ApiParam(value = "应用App主键ID", name = "appId")String appId,HttpServletResponse response) throws Exception {
try {
// 清空response
response.reset();
// 设置response的Header
response.setContentType("application/vnd.android.package-archive;");
response.setHeader("Content-disposition", "attachment; filename=" + new String(apkInfoVO.getFileName().getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(getFileLength(apkInfo.getFilePath())));
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
Utils.setOutputStream(apkInfo.getFilePath(), outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
response.reset();
throw new Exception(e);
}
return WebDTO.success();
}
//获取文件长度
private int getFileLength(String filePath) {
HttpURLConnection connection = null;
URL conurl = null;
try {
String url =Constant.getName("HTTP")+filePath;
conurl = new URL(url);
connection = (HttpURLConnection) conurl.openConnection();
int fileLength = connection.getContentLength();
return fileLength;
}catch (Exception e) {
// TODO: handle exception
}
return 0;
}
上面的这种写法,要求前端传的是单独的参数,retrofit如下传参
@FormUrlEncoded
@POST("###")
Observable<NewsResponse> newsListQuery(@Field("currentPage") int currentPage,@Field("size") int size);
2.如果后台用这种方式,传的是json字符串
@RequestMapping(value = "/downloadApp", method = RequestMethod.POST)
@ApiOperation(httpMethod = "POST", value = "下载文件", produces = MediaType.APPLICATION_JSON_VALUE)
public Object download(@RequestBody @ApiParam(value="用户Id",name="appId" ,required = true) String paramStr,HttpServletResponse response) throws Exception {
try {
JSONObject object = JSONObject.parseObject(paramStr);
String appId = object.getString("appId");
...
}
前端应如下写,这次用的okhtttp请求,使用requestBody
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("appId", appCenter.getAppId());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject.toString();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonString);
this.okHttpClient.newCall(new Request.Builder()).url(url).post(requestBody).build()).enqueue(new Callback() {}