HttpClient 实现上传下载

本文介绍了一种使用Java实现的文件上传和下载的方法。通过创建HttpClient实例,利用MultipartEntityBuilder进行多文件上传,并设置了浏览器兼容模式以避免文件名乱码问题。同时,也提供了从URL下载文件到本地的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
	 * 上传文件
	 * @param filePathList 文件路径
	 * @param filePath 在文件服务器 保存的文件夹名 例:“/poi_thumbnail/”
	 */
	public static void postFile(List<String> filePathList, String filePath)
			throws ParseException, IOException {

		CloseableHttpClient httpClient = HttpClients.createDefault();
		try {

			MultipartEntityBuilder build = MultipartEntityBuilder.create(); // 创建多部分的生成器
			build.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); // 浏览器兼容模式
			build.setCharset(CharsetUtils.get("UTF-8"));

			for (int i = 0; i < filePathList.size(); i++) {  //多文件上传
				build.addPart("uploadFile" + i,
						new FileBody(new File(filePathList.get(i))));
			}
			
			//从指定的文本中创建一个StringBody。MIME 类型设置为“text / plain”。使用 {@linkplain Consts#ASCII ASCII} 字符集。
			build.addPart("filePath",
					new StringBody(filePath, ContentType.create("text/plain",
							Consts.UTF_8)));

			// 把一个普通参数和文件上传给下面这个地址 是一个 servlet
			HttpPost httpPost = new HttpPost(GlobalContract.UPLOAD_URL);
			// 以浏览器兼容模式运行,防止文件名乱码。
			HttpEntity reqEntity = build.build();
			httpPost.setEntity(reqEntity);

//			System.out.println("发起请求的页面地址 " + httpPost.getRequestLine());
			// 发起请求 并返回请求的响应
			CloseableHttpResponse response = httpClient.execute(httpPost);
			try {
				// 打印响应状态
//				System.out.println(response.getStatusLine());
				// 获取响应对象
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					// 打印响应长度
//					System.out.println("Response content length: "
//							+ resEntity.getContentLength());
					// 打印响应内容
//					System.out.println(EntityUtils.toString(resEntity,
//							Charset.forName("UTF-8")));
				}
				// 销毁
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
			}
		} finally {
			httpClient.close();
		}
	}

	/**
	 * 下载文件
	 * 
	 * @param url
	 *            http://www.xxx.com/img/333.jpg
	 * @param destFileName
	 *            xxx.jpg/xxx.png/xxx.txt
	 */
	public static void getFile(String url, String destFileName)
			throws ClientProtocolException, IOException {
		
		CloseableHttpClient httpclient = HttpClients.createDefault(); //创建 HttpClient 的实例
		HttpGet httpget = new HttpGet(url);  //创建某种连接方法的实例
		HttpResponse response = httpclient.execute(httpget); // 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
		HttpEntity entity = response.getEntity();  //读  response 获取此响应的消息实体(如果有的话)。
		InputStream in = entity.getContent();	   // 返回实体的内容流。
		File file = new File(destFileName);
		try {
			FileOutputStream fout = new FileOutputStream(file); //创建一个 向指定 File 对象表示的文件中 写入数据的文件输出流。
			int l = -1;
			byte[] tmp = new byte[1024];
			while ((l = in.read(tmp)) != -1) {
				fout.write(tmp, 0, l);
				// 注意这里如果用OutputStream.write(buff)的话,图片会失真,大家可以试试
			}
			fout.flush();
			fout.close();
		} finally {
			// 关闭低层流。
			in.close();
		}
		httpclient.close();  //释放连接。无论执行方法是否成功,都必须释放连接
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值