android开发-----网络编程(使用httppost进行提交数据)

PS:由于某些原因开始进行android开发学习,对于javaee方便就接触比较少了,之前还有学过三大框架但是都还没记录,等什么时候闲点再记吧,顺便还能复习下。这篇文章主要是要记录怎么将数据通过post提交发送给服务端,以及接收服务端发送过来的数据。。。


需求:1.将手机的数据库文件发送到服务端,服务端保存  2.将服务端保存的数据发送回手机,手机将该文件覆盖已有的数据库文件

难点:如何将普通数据以及文件数据发送出去

解决办法:

1.使用HttpPost 封装数据内容

2.使用MultipartEntity封装数据,再放入post请求中

3.使用HttpClient将post发送出去


代码:(此处只是演示代码,需要添加一些健壮性的语句)

1.需要导入MultipartEntity相关的工具包

2.android客户端代码:

发送数据:(使用该方法同时可以实现传输图片或其他文件以及普通字符串数据)

		File dbFile = this.getDatabasePath("note.db");//1.获取数据库文件
		
		HttpPost post = new HttpPost(SERVER_UP_URL);//2.指定post连接的url
		HttpClient client = new DefaultHttpClient();//3.创建发送请求的client对象
		HttpResponse response;//4.用于获取响应对象
		
		MultipartEntity entity = new MultipartEntity();//5.创建一个封装数据的实体(该代码默认将请求的类型定义为multipart/form-data)
																					//该类型允许发送文件数据
		try {
			FileBody body = new FileBody(dbFile);//将一个文件封装,便于将数据存入实体
			entity.addPart("file", body);					//6.为数据实体填充数据,通过类似键值对的方式填充
			entity.addPart("name", new StringBody("halm"));		//第一个参数为键(服务器request获取的参数名),第二个参数为值内容
																//普通字符串,文件用不同的类进行封装
			post.setEntity(entity);//7.为post请求封装数据实体以及提交类型
			response = client.execute(post);//8.发送post请求
			int status = response.getStatusLine().getStatusCode();//9.获取服务端响应状态码来判断是否交互成功
			if(status != 200){
				Toast.makeText(ListViewActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
				return;
			}
			Toast.makeText(ListViewActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

接收数据:

		File dbFile = this.getDatabasePath("note.db");//1.先获取本地数据库文件
		if(dbFile.exists()){
			dbFile.delete();//2.判断是否存在,如果存在则删除(便于覆盖)
		}
		try {
			dbFile.createNewFile();//3.到此处都不存在该文件,所以就需要创建该数据库文件
			OutputStream out = new FileOutputStream(dbFile);//4.设置一个写的流,用于将数据写到文件内
			
			URL url = new URL(SERVER_DOWN_URL);//5.使用URL连接网站
			URLConnection conn = url.openConnection();//6.拿到该URL的连接
			InputStream in = conn.getInputStream();//7.通过连接获取读取流,用于获取接收到的数据
			byte buff[] = new byte[1024];
			int len;
			while((len=in.read(buff))>0){
				out.write(buff, 0, len);//8.将接收到的数据写到数据库文件中
			}
			in.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}


3.服务端代码

接收数据并保存

		try {
			//判断提交的方式
			if(!ServletFileUpload.isMultipartContent(request)){
				System.out.println("错误提交");
				return;
			}
			//以下是文件上传的代码
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setRepository(new File(request.getSession().getServletContext().getRealPath("/WEB-INF/temp")));
	
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			upload.setFileSizeMax(1024*1024*500);

			List<FileItem> files = upload.parseRequest(request);
			for (FileItem fileItem : files) {
				if(fileItem.isFormField()){
					String name = fileItem.getFieldName();
					String value = fileItem.getString("UTF-8");
					System.out.println(name + ":" + value);
					continue;
				}
				String filename = fileItem.getName();
				System.out.println("filename+"+ filename);
				InputStream in = fileItem.getInputStream();
				OutputStream out = new FileOutputStream(new File("c://"+filename));
				byte buff[] = new byte[1024];
				int len;
				while((len=in.read(buff)) > 0){
					out.write(buff, 0, len);
				}
				in.close();
				out.close();
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}

发送数据

		//将数据写出
		File file = new File("c://note.db");
		if(file.exists()){
			return;
		}
		InputStream in = new FileInputStream(file);
		byte buff[] = new byte[1024];
		int len;
		
		while((len=in.read(buff))>0){
			response.getOutputStream().write(buff, 0, len);
		}
		
		in.close();
		System.out.println("发送了");






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章