通过URL下载文件

做项目过程中,需要根据别人提供的URL去下载附件。
			// 建立连接
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
			
			HttpMethod method = null;
			// 获得文件流
			method = new GetMethod(url);
			client.executeMethod(method);
			
			// 打印http交互信息
			printHttpInteractInfo(method);
			
		    // 获取文件流
		    InputStream inputStream = method.getResponseBodyAsStream();


开始是用的apache的httpclient组件,后来发现还需支持FTP协议的URL,还有httpclient用get请求不支持包含中文的url。

后来发现java本身的URLConnection很好的满足项目的需求,因为只是简单的去请求,然后获得响应的内容。

			URL url = new URL(url);
			
			URLConnection conn = url.openConnection();
			conn.setConnectTimeout(5000);
			// 获取文件流
			InputStream inputStream = conn.getInputStream();


还有我发现InputStream.available()获取字符流长度的时候,总是为0,而conn.getContentLength()可以获取到文件的长度。

猜你喜欢

转载自bobfan.iteye.com/blog/2224266