Android网络编程(下)--- 框架AsyncHttpClient/上传文件

1.AsyncHttpClient
   android-async-http 开源框架可以使我们轻松地获取网络数据或者向服务器发送数据.。
   最关键的是,它是异步框架,在底层使用线程池处理并发请求,效率很高,使用又特别简单。

   以往我们在安卓上做项目,比如要下载很多图片、网页或者其他的资源,多数开发者会选择一个线程一个下载任务这种模型。
   因为安卓集成自带的HttpClient或者java的URL/UrlConnection ,默认都是阻塞式操作。
   这种模型效率不高,对并发要求高的应用来讲,并不适用。

   AsyncHttpClient作为android-async-http框架的一个核心应用类,使用简单,可以处理文本、二进制等各种格式的web资源。


2.使用AsyncHttpClient上传文件到服务器
  1)服务器端需要使用框架 --- commons-fileupload-1.2.1.jar   commons-io-1.4.jar
    工程下导入jar包并build path

  2)编写Servlet

  3) 安卓客户端编写

      清单中添加联网权限
      <uses-permission android:name="android.permission.INTERNET" />

      编写类,核心代码
      AsynHttpClient client = new AsynHttpClient();
      //执行post请求
      client.post(url, params, responseHandler);
      三个参数分别代表:url地址,请求参数,响应
      
      请求参数:
      RequestParams params = new RequestParams();
      params.put("file", file);

      响应 --- 匿名内部类,重写onSuccess onFailure方法:
      new AsyncHttpResponseHandler(){...};

代码:


服务器端FileUploadServlet

@WebServlet("/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public FileUploadServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			String realpath = request.getSession().getServletContext()
					.getRealPath("/files");
			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");
			try {
				List<FileItem> items = upload.parseRequest(request);
				for (FileItem item : items) {
					if (item.isFormField()) {
						String name1 = item.getFieldName();// 得到请求参数的名称
						String value = item.getString("UTF-8");// 得到参数值
						System.out.println(name1 + "=" + value);
					} else {
						item.write(new File(dir, System.currentTimeMillis()
								+ item.getName().substring(
										item.getName().lastIndexOf("."))));
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			doGet(request, response);
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

客户端

	/**
	 * 上传文件
	 * 
	 * @param v
	 */
	public void upload(View v) {

		try {
			// 客户端
			AsyncHttpClient client = new AsyncHttpClient();
			// 上传的文件
			File file = new File(Environment.getExternalStorageDirectory(),
					"a.jpg");
			// url
			String url = "http://10.0.2.2:8080/web/FileUploadServlet";
			// 请求参数
			RequestParams params = new RequestParams();
			params.put("file", file);
			// 执行post请求,上传文件,获取响应
			client.post(url, params, new AsyncHttpResponseHandler() {

				// 上传成功
				@Override
				public void onSuccess(int statusCode, Header[] headers,
						String content) {
					super.onSuccess(statusCode, headers, content);
					Toast.makeText(getApplicationContext(), "上传成功", 0).show();
				}

				// 上传失败
				@Override
				public void onFailure(Throwable error, String content) {
					super.onFailure(error, content);
					Toast.makeText(getApplicationContext(), "上传失败", 0).show();
				}

			});
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值