上一篇专题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 &#