android服务端客户端(三)

上一节做了表单上传图片到服务端的demo。这一节来做从服务端下载图片的demo。

服务端,在BeautyDao中写一个在数据库中查询所有beauty的方法——queryAll()。

// 查询所有的beauty
	public List<Beauty> queryAll() {

		List<Beauty> beauties = new ArrayList<Beauty>();

		try {
			// 获得连接
			Connection conn = DBUtil.getConn();
			PreparedStatement pst = conn.prepareStatement("select * from beauty");
			ResultSet rs = pst.executeQuery();
			while (rs.next()) {
				girls.add(new Beauty(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)));

			}
			// 关闭资源
			DBUtil.close(conn, pst, rs);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return beauties;

	}

构造一个GetAllBeautyServlet,客户端通过请求服务端,获得服务端返回的json数据,通过解析json数据获得其中的entity,从而达到下载的目的。

通过queryAll查询出所有beauty,将查询出的信息转成类似下面的json数据:

{ beauties:[ {id:1,name:\"bobo\",description:\"xxx\",imagename:\"xxx\"},

{},{} ] }

转变思路:[ {} , {} , {} ] ,客户端就可以以数组的方式处理这个json数据。

                StringBuffer sb = new StringBuffer();
		sb.append("[");
		
		for (int i = 0; i <= list.size() - 1; i++) {
			Girl g = list.get(i);
			if (i == list.size() - 1) {
				// 如果是最后一个,后面就没有,号
				sb.append("{id:" + g.getId() + ",name:\"" + g.getName() + "\",description:\""
						+ g.getDescription() + "\",imagename:\"" + g.getImageName() + "\"}");

			}else{
				sb.append("{id:" + g.getId() + ",name:\"" + g.getName() + "\",description:\""
						+ g.getDescription() + "\",imagename:\"" + g.getImageName() + "\"},");
			}
		}

		sb.append("]");
		
		String jsonContent = sb.toString();
		//输出给客户端
		resp.setContentType("text/html;charset=UTF-8");
		resp.getWriter().write(jsonContent);


接下来我们要构建android客户端代码。点击按钮实现下载。

android端程序也需要一个beauty实体,基本跟服务端的Beauty实体一致。

点击按钮,采用异步任务实现下载。

要注意这里的请求路径,打开cmd窗口,通过ip config -all 命令查询ip地址,因为我这里是通过adb connect将手机连接到电脑,所以使用的是无线网络的ip。

            public class MyTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			// 开始连接网络。
			/*
			 * URL和HttpClient都能实现网络连接。
			 * 但是HttpClient实现的过程更简单,所以我们采用HttpClient实现网络连接。
			 */

			String path = "http://192.168.1.101:8080/TT_Server/GetAllBeautyServlet";

			// 创建客户端(打开浏览器)
			HttpClient client = new DefaultHttpClient();

			// 构造post或者get请求。
			HttpGet get = new HttpGet(path);

			HttpResponse response = null;
			try {
				response = client.execute(get);
				if (response.getStatusLine().getStatusCode() == 200) {
					// 正确获得数据。
					String jsonContent = EntityUtils.toString(
							response.getEntity(), "UTF-8");
					Log.i("TT",jsonContent );

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			
		}

	}
通过第三方jar包解析获得的json数据。这里采用fastjson.jar。需要下载的请点 fastjson.jar下载


回到服务端,构建一个GetImageByNameServlet,根据图片名称获得图片数据

                //获取客户端发送来的图片名称
		String imageName = req.getParameter("imageName");
		//通过输入流读进来
		FileInputStream fis = new FileInputStream("C:\\"+imageName);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len=fis.read(buffer))!=-1) {
			bos.write(buffer,0,len);
			
		}
		byte[] allData = bos.toByteArray();
		//关闭资源
		fis.close();
		bos.close();
		
		//将图片发送到客户端
		resp.getOutputStream().write(allData);

在android端,就可以通过这个Servlet获得bitmap,在Beauty实体中增加一个属性bitmap,用来设置bitmap数据。

           beauties = (List<Beauty>) JSON.parseArray(jsonContent,Beauty.class);
		for (Beauty beauty : beauties) {
		// Log.i("TZ",beauty.toString() );
		// 获得妹子的图片名称,然后下载图片数据。
		String getImagePath = "http://192.168.1.101:8080/TT_Server/GetImageByNameServlet?imageName="
				+ beauty.getImageName();
		HttpGet imageGet = new HttpGet(getImagePath);
		HttpResponse imageResponse = client.execute(imageGet);
		if (imageResponse.getStatusLine().getStatusCode() == 200) {
			Bitmap bitmap = BitmapFactory
				.decodeStream(imageResponse.getEntity()
				.getContent());
			girl.setBitmap(bitmap);
			}

		}
异步任务实际上是封装了线程和Handler的功能,分别可以用来连接网络和更新UI。在doInBackground方法中连接网络,在onPostExecute更新UI。

我们在界面中增加一个listview用来显示下载的数据。写一个Adapter。

        @Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View root=inflater.inflate(R.layout.sister_layout, null);
		
		ImageView imageView=(ImageView)root.findViewById(R.id.image);
		TextView tvName=(TextView)root.findViewById(R.id.tvName);
		TextView tvDescription=(TextView)root.findViewById(R.id.tvDescription);
		
		Girl g = girls.get(position);
		
		imageView.setImageBitmap(g.getBitmap());
		tvName.setText( g.getName() );
		tvDescription.setText( g.getDescription() );
		
		return root;
	}

在onPostExecute方法中setAdapter。

                @Override
		protected void onPostExecute(Void result) {
			if (girls != null) {
				// 将girls的内容显示到桌面。
				mAdapter = new MySisterAdapter(girls, MainActivity.this);
				listView.setAdapter(mAdapter);
			}
		}

记得加上联网权限:<uses-permission android:name="android.permission.INTERNET"/>






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值