欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android自更新时下载出现的问题 博客分类: Java 下载downloadHttpStatusandroid 下载 

程序员文章站 2024-03-21 22:04:58
...

之前做过一个电视台app,电视台app每次启动时会访问服务器,判断是否需要下载新版本

但是下载时老是下载失败,apk包总是下载不下来.到底是什么原因呢?

服务器下载接口如下:

/***
	 * 下载apk
	 * @param path
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/download"/*, headers = {"content-type=application/json"}*/)
    public ResponseEntity<byte[]> download( String path,HttpServletRequest request) throws IOException {
    	AccessLog accessLog=logInto(request);
		accessLog.setDescription("下载客户端");
    	if(!ValueWidget.isNullOrEmpty(request.getContentType())&& request.getContentType().toLowerCase().contains("application/json")){
	    	String requestStr=WebServletUtil.getRequestQueryStr(request, null);
	    	System.out.println(requestStr);
	    	Map queryMap=JSONPUtil.getMapFromJson(requestStr);
	    	if(!ValueWidget.isNullOrEmpty(queryMap)){
	    		path=(String) queryMap.get("path");
	    	}
    	}
    	if(ValueWidget.isNullOrEmpty(path)){
    		System.out.println("download failed");
    		accessLog.setOperateResult("下载失败,没有传递path参数");
    		logSave(accessLog, request);
    		return null;
    	}
    	String realpath =WebServletUtil.getUploadPath(request, "upload/download/apk", request
				.getSession().getServletContext(), Constant2.SRC_MAIN_WEBAPP);
    	if(!realpath.endsWith(File.separator)){
    		realpath=realpath+File.separator;
    	}
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        String fullpath=realpath+path;
        
        System.out.println("download path:"+fullpath);
        headers.set(Constant2.CONTENT_DISPOSITION,WebServletUtil.getContentDisposition(true, path));
        accessLog.setOperateResult("下载成功,下载文件:"+fullpath+" ,size:"+FileUtils.getFileSize2(fullpath));
		logSave(accessLog, request);
        return new ResponseEntity<byte[]>(FileUtils.getBytes4File(fullpath),
                                          headers, HttpStatus.CREATED);
    }

 

安卓端调用的下载方法(核心代码)如下:

/***
	 * 
	 * @param huc
	 * @param sendBytes
	 * @param mode
	 * @param isWrite2file
	 *            : 是否写入文件
	 * @return
	 * @throws Exception
	 */
	private static byte[] connection(HttpURLConnection huc,
			boolean isWrite2file, Object file, String sizeHeadKey)
			throws Exception {
		int resCode = huc.getResponseCode();

		if (resCode == HttpURLConnection.HTTP_OK) {
			int contentLength = 0;
			if (ValueWidget.isNullOrEmpty(sizeHeadKey)) {// 若header中没有size
				contentLength = huc.getContentLength();
			} else {
				String sizeHeaderValue = huc.getHeaderField(sizeHeadKey);
				if (!ValueWidget.isNullOrEmpty(sizeHeaderValue)) {
					contentLength = Integer.parseInt(sizeHeaderValue);
				}

			}
			if (isDetail) {
				System.out
						.println("[connection]contentLength:" + contentLength);
				responseHeaderFields = huc.getHeaderFields();
				String downloadHeader = "Content-Disposition";
				if (!ValueWidget.isNullOrEmpty(responseHeaderFields)) {
					List<String> ContentDispositions = responseHeaderFields
							.get(downloadHeader);
					if (!ValueWidget.isNullOrEmpty(ContentDispositions)) {
						String ContentDisposition = ContentDispositions.get(0);
						System.out.println("ContentDisposition:"
								+ ContentDisposition);
						System.out.println("ContentDisposition convertISO2UTF:"
								+ SystemHWUtil
										.convertISO2UTF(ContentDisposition));
						System.out
								.println("ContentDisposition convertISO2GBK: "
										+ SystemHWUtil
												.convertISO2GBK(ContentDisposition));
					}
				}
				for (Object obj : responseHeaderFields.keySet()) {
					List<String> list = responseHeaderFields.get(obj);
					if (!ValueWidget.isNullOrEmpty(list)) {
						System.out.println(obj + " : "
								+ SystemHWUtil.formatArr(list, ";"));
					}
				}
				System.out
						.println("[connection]contentLength:" + contentLength);
			}
			if (contentLength > 0) {
				if (isDetail)
					System.out
							.println("[HttpSocketUtil.connection]httputil,contentLength:"
									+ contentLength);
				// return readData(huc);
				File file2 = null;
				if (isWrite2file) {
					if (file instanceof File) {
						file2 = (File) file;
						writeFileFromLength(huc, contentLength, file2);
						if (isDetail) {
							System.out.println("download success:"
									+ file2.getAbsolutePath());
						}
					} else {
						writeFileFromLength(huc, contentLength,
								(OutputStream) file);
					}
					return null;
				} else {
					return readDataFromLength(huc, contentLength);
				}
			} else {
				if (isWrite2file) {
					InputStream in = huc.getInputStream();
					FileUtils.writeIn2OutputCloseAll(in, new FileOutputStream(
							(File) file));
					if (isDetail) {
						System.out.println("download success:"
								+ ((File) file).getAbsolutePath());
					}
					return null;
				}
				return readData(huc);
			}
		} else {
			System.out.println("response Code:" + resCode);
		}
		return null;
	}

 

代码本身是没有逻辑错误的.花了很长时间才找到原因,是定义的response的status code不一致.


android自更新时下载出现的问题
            
    
    博客分类: Java 下载downloadHttpStatusandroid 下载 
 
android自更新时下载出现的问题
            
    
    博客分类: Java 下载downloadHttpStatusandroid 下载 
 

后台设置的status code是201,而android端判断的status code是200,不一致导致下载流程没有走到下载逻辑.

修改方法:把后台的status code改为200 就OK了

 

  • android自更新时下载出现的问题
            
    
    博客分类: Java 下载downloadHttpStatusandroid 下载 
  • 大小: 32.8 KB
  • android自更新时下载出现的问题
            
    
    博客分类: Java 下载downloadHttpStatusandroid 下载 
  • 大小: 46.9 KB