Android开发之网络请求通信专题(二):基于HttpClient的文件上传下载

这篇博客详细介绍了在Android开发中如何使用HttpClient进行文件的上传和下载操作,包括Android端的文件上传处理、服务端的dopost响应以及文件下载流程。此外,还探讨了httpclient类的封装,包括逻辑封装、HTTP访问管理者、AsyncTask任务以及在Activity中的应用。
摘要由CSDN通过智能技术生成

上一篇专题Android开发之网络请求通信专题(一):基于HttpURLConnection的请求通信我们讲解了如何使用httpurlconnection来实现基本的文本数据传输。一般在实际开发中我们可以用于传输xml或者json格式的数据。今天我们来讲解另外一种http网络请求的方式:httpclient,并实现文件的上传和下载。

在这里插个题外话,其实这些网络请求有很多第三方jar包可以使用,这些包都封装得很好了。如果只是想使用,我们就直接拿别人得jar包来用就好。博主这里推荐一个叫xutils的工具类,这个玩意其实好用,相信很多人都知道,这个工具类是博主的一个同学的同事写的。后续博主还会写一个图片专题中,也会讲解到xutils里面的图片类的实现原理。好了,进入今天的正题。

和上一篇专题一样,我们先讲解两种请求方式的基本用法,然后再深入进行封装使用。


一、基于httpclient实现文件的上传

我们先看看最基本的上传代码

1、Android端的文件上传

/**
	 * @Title: updateFile
	 * @Description: 文件上传
	 * @throws
	 */
	private void updateFile() {
		//新建一个httpclient类
		HttpClient httpclient = new DefaultHttpClient();
		//用post方式实现文件上传
		HttpPost post = new HttpPost(
				"http://192.168.1.107:10010/MINATest/servlet/UploadServlet");
		//拿到上传的图片
		String filePath = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/justice.jpg";
		//处理上传的文件
		FileBody fileBody = new FileBody(new File(filePath));
		StringBody stringBody = null;
		try {
			stringBody = new StringBody("文件的描述");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		MultipartEntity entity = new MultipartEntity();
		entity.addPart("file", fileBody);
		entity.addPart("desc", stringBody);
		post.setEntity(entity);
		HttpResponse response = null;
		try {
			response = httpclient.execute(post);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
			
			//拿到返回的实体,一般而言,用post请求方式返回的流是用这个实体拿到,在这里不需要所以博主就不写了。
			HttpEntity entitys = response.getEntity();
			if (entity != null) {
				System.out.println(entity.getContentLength());
				try {
					System.out.println(EntityUtils.toString(entitys));
				} catch (ParseException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		httpclient.getConnectionManager().shutdown();
	}

2、服务端dopost处理

/**
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		boolean isMulti = ServletFileUpload.isMultipartContent(request);
		if (isMulti) {
			String realPath = request.getSession().getServletContext()
					.getRealPath("/vioce");
			System.out.println(realPath);
			File dir = new File(realPath);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			String fileName = null;
			try {
				List<FileItem> items = upload.parseRequest(request);
				for (FileItem item : items) {
					if (item.isFormField()) {
						String name = item.getFieldName();
						String value = item.getString("UTF-8");
						System.out.println(name + "-" + value);
					} else {
						item.write(new File(dir, item.getName()));
						fileName &#
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值