@Override @SuppressWarnings("fallthrough") public boolean stopDownload() { switch (getStatus()) { case IN_PROGRESS: if (request != null) { request.abort(); } status = TemplateDownloader.Status.ABORTED; return true; case UNKNOWN: case NOT_STARTED: case RECOVERABLE_ERROR: case UNRECOVERABLE_ERROR: case ABORTED: status = TemplateDownloader.Status.ABORTED; case DOWNLOAD_FINISHED: File f = new File(toFile); if (f.exists()) { f.delete(); } return true; default: return true; } }
/** * 根据url获取ResponseBody,method=get * * @param url exp:http://192.168.1.1:8080/dir/target.html * @return 以byte[]的方式放回 */ public static byte[] getDataFromUrl(String url, int timeout) { if (StringUtils.isBlank(url)) { logger.error("url is blank!"); return null; } HttpClient httpClient = new HttpClient(); // 连接超时 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(8000); // 等待数据返回超时 httpClient.getParams().setSoTimeout(timeout); GetMethod method = new GetMethod(url); // fix连接结束后不能正确关闭的问题 // method.setRequestHeader("Connection", "close"); // 如果发生错误则连续尝试1次 method .getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); try { int statusCode = httpClient.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { return method.getResponseBody(); } else { throw new RuntimeException( "http request error,return code:" + statusCode + ",msg:" + new String(method.getResponseBody())); } } catch (HttpException e) { method.abort(); logger.error(e.getMessage()); } catch (IOException e) { method.abort(); logger.error(e.getMessage()); } finally { // Release the connection. method.releaseConnection(); } return null; }
protected int downloadFile(OwnCloudClient client, File targetFile) throws HttpException, IOException, OperationCancelledException { int status = -1; boolean savedFile = false; mGet = new GetMethod(client.getWebdavUri() + WebdavUtils.encodePath(mRemotePath)); Iterator<OnDatatransferProgressListener> it = null; FileOutputStream fos = null; try { status = client.executeMethod(mGet); if (isSuccess(status)) { targetFile.createNewFile(); BufferedInputStream bis = new BufferedInputStream(mGet.getResponseBodyAsStream()); fos = new FileOutputStream(targetFile); long transferred = 0; Header contentLength = mGet.getResponseHeader("Content-Length"); long totalToTransfer = (contentLength != null && contentLength.getValue().length() > 0) ? Long.parseLong(contentLength.getValue()) : 0; byte[] bytes = new byte[4096]; int readResult = 0; while ((readResult = bis.read(bytes)) != -1) { synchronized (mCancellationRequested) { if (mCancellationRequested.get()) { mGet.abort(); throw new OperationCancelledException(); } } fos.write(bytes, 0, readResult); transferred += readResult; synchronized (mDataTransferListeners) { it = mDataTransferListeners.iterator(); while (it.hasNext()) { it.next() .onTransferProgress( readResult, transferred, totalToTransfer, targetFile.getName()); } } } if (transferred == totalToTransfer) { // Check if the file is completed savedFile = true; Header modificationTime = mGet.getResponseHeader("Last-Modified"); if (modificationTime == null) { modificationTime = mGet.getResponseHeader("last-modified"); } if (modificationTime != null) { Date d = WebdavUtils.parseResponseDate((String) modificationTime.getValue()); mModificationTimestamp = (d != null) ? d.getTime() : 0; } else { Log_OC.e( TAG, "Could not read modification time from response downloading " + mRemotePath); } mEtag = WebdavUtils.getEtagFromResponse(mGet); if (mEtag.length() == 0) { Log_OC.e(TAG, "Could not read eTag from response downloading " + mRemotePath); } } else { client.exhaustResponse(mGet.getResponseBodyAsStream()); // TODO some kind of error control! } } else { client.exhaustResponse(mGet.getResponseBodyAsStream()); } } finally { if (fos != null) fos.close(); if (!savedFile && targetFile.exists()) { targetFile.delete(); } mGet.releaseConnection(); // let the connection available for other methods } return status; }