操作抓取网络资源

  在实际开发过程中,大家难免遇到抓取网络资源的操作,列如:抓取相册图片,获得网络的MP3,或者是Flash等资源。下边就写了一个读取网络资源的事列:
private boolean upload(String srcUrl, String fileName, int fileSize) {
		URL url = null;
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		try {
			byte[] buf = new byte[BUFFER_SIZE];
			url = new URL(srcUrl);
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.setDoOutput(true);
			httpUrl.setRequestMethod("GET");
			httpUrl.setConnectTimeout(30 * 1000);//set ms in unit
			httpUrl.setReadTimeout(30 * 1000); 
			if (httpUrl.getContentLength() > fileSize * 1024) {
				logger.error("upload file gt file's size!");
				return false;
			}
			bis = new BufferedInputStream(httpUrl.getInputStream());
			File file = new File(fileName);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			fos = new FileOutputStream(fileName);
			
			int size = 0;
			while ((size = bis.read(buf)) != -1) {
				fos.write(buf, 0, size);
			}
			
			fos.flush();
			httpUrl.disconnect();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return false;
		} finally {
			if (null != fos) {
				try {
					fos.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
			
			if (null != bis) {
				try {
					bis.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}
			
			if (null != httpUrl) {
				httpUrl.disconnect();
			}
		}
		return true;
	}

你可能感兴趣的:(Flash)