在Android里面或者J2EE后臺需要趴別人網(wǎng)站數(shù)據(jù),模擬表單提交是一件很常見的事情,但是在Android里面要實(shí)現(xiàn)多文件上傳,還要夾著普通表單字段上傳,這下可能就有點(diǎn)費(fèi)勁了,今天花時(shí)間整理了一個(gè)工具類,主要是借助于HttpClient,其實(shí)也很簡單,看一下代碼就非常清楚了
HttpClient工具類:
HttpClientUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
|
package cn.com.ajava.util; import java.io.File; import java.io.Serializable; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; /** * HttpClient工具類 * * @author 曾繁添 * @version 1.0 */ public class HttpClientUtil { public final static String Method_POST = "POST" ; public final static String Method_GET = "GET" ; /** * multipart/form-data類型的表單提交 * * @param form * 表單數(shù)據(jù) */ public static String submitForm(MultipartForm form) { // 返回字符串 String responseStr = "" ; // 創(chuàng)建HttpClient實(shí)例 HttpClient httpClient = new DefaultHttpClient(); try { // 實(shí)例化提交請求 HttpPost httpPost = new HttpPost(form.getAction()); // 創(chuàng)建MultipartEntityBuilder MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); // 追加普通表單字段 Map<String, String> normalFieldMap = form.getNormalField(); for (Iterator<Entry<String, String>> iterator = normalFieldMap.entrySet().iterator(); iterator.hasNext();) { Entry<String, String> entity = iterator.next(); entityBuilder.addPart(entity.getKey(), new StringBody(entity.getValue(), ContentType.create( "text/plain" , Consts.UTF_8))); } // 追加文件字段 Map<String, File> fileFieldMap = form.getFileField(); for (Iterator<Entry<String, File>> iterator = fileFieldMap.entrySet().iterator(); iterator.hasNext();) { Entry<String, File> entity = iterator.next(); entityBuilder.addPart(entity.getKey(), new FileBody(entity.getValue())); } // 設(shè)置請求實(shí)體 httpPost.setEntity(entityBuilder.build()); // 發(fā)送請求 HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); // 取得響應(yīng)數(shù)據(jù) HttpEntity resEntity = response.getEntity(); if ( 200 == statusCode) { if (resEntity != null ) { responseStr = EntityUtils.toString(resEntity); } } } catch (Exception e) { System.out.println( "提交表單失敗,原因:" + e.getMessage()); } finally { httpClient.getConnectionManager().shutdown(); } return responseStr; } /** 表單字段Bean */ public class MultipartForm implements Serializable { /** 序列號 */ private static final long serialVersionUID = -2138044819190537198L; /** 提交URL **/ private String action = "" ; /** 提交方式:POST/GET **/ private String method = "POST" ; /** 普通表單字段 **/ private Map<String, String> normalField = new LinkedHashMap<String, String>(); /** 文件字段 **/ private Map<String, File> fileField = new LinkedHashMap<String, File>(); public String getAction() { return action; } public void setAction(String action) { this .action = action; } public String getMethod() { return method; } public void setMethod(String method) { this .method = method; } public Map<String, String> getNormalField() { return normalField; } public void setNormalField(Map<String, String> normalField) { this .normalField = normalField; } public Map<String, File> getFileField() { return fileField; } public void setFileField(Map<String, File> fileField) { this .fileField = fileField; } public void addFileField(String key, File value) { fileField.put(key, value); } public void addNormalField(String key, String value) { normalField.put(key, value); } } } |
服務(wù)器端實(shí)現(xiàn)文件上傳、并且讀取參數(shù)方法:(借助于Apache的fileupload組件實(shí)現(xiàn),實(shí)現(xiàn)了獲取表單action后面直接拼接參數(shù)、表單普通項(xiàng)目、文件項(xiàng)目三種字段獲取方法)
后臺我就直接寫了一個(gè)Servlet,具體代碼如下:
ServletUploadFile.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
package cn.com.ajava.servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * 文件上傳Servlet * @author 曾繁添 */ public class ServletUploadFile extends HttpServlet { private static final long serialVersionUID = 1L; // 限制文件的上傳大小 1G private int maxPostSize = 1000 * 1024 * 10 ; public ServletUploadFile() { super (); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); String contextPath = request.getSession().getServletContext().getRealPath( "/" ); String webDir = "uploadfile" + File.separator + "images" + File.separator; String systemPath = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ systemPath + "/" ; request.setCharacterEncoding( "UTF-8" ); response.setContentType( "text/html;charset=UTF-8" ); try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold( 1024 * 4 ); // 設(shè)置寫入大小 ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxPostSize); // 設(shè)置文件上傳最大大小 System.out.println(request.getContentType()); //獲取action后面拼接的參數(shù)(如:http://www.baidu.com?q=android) Enumeration enumList = request.getParameterNames(); while (enumList.hasMoreElements()){ String key = (String)enumList.nextElement(); String value = request.getParameter(key); System.out.println(key+ "=" +value); } //獲取提交表單項(xiàng)目 List listItems = upload.parseRequest(request); Iterator iterator = listItems.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); //非普通表單項(xiàng)目 if (!item.isFormField()) { //獲取擴(kuò)展名 String ext = item.getName().substring(item.getName().lastIndexOf( "." ), item.getName().length()); String fileName = System.currentTimeMillis() + ext; File dirFile = new File(contextPath + webDir + fileName); if (!dirFile.exists()) { dirFile.getParentFile().mkdirs(); } item.write(dirFile); System.out.println( "fileName:" + item.getName() + "=====" + item.getFieldName() + " size: " + item.getSize()); System.out.println( "文件已保存到: " + contextPath + webDir + fileName); //響應(yīng)客戶端請求 out.print(basePath + webDir.replace( "\\" , "/" ) + fileName); out.flush(); } else { //普通表單項(xiàng)目 System.out.println( "表單普通項(xiàng)目:" +item.getFieldName()+ "=" + item.getString( "UTF-8" )); // 顯示表單內(nèi)容。item.getString("UTF-8")可以保證中文內(nèi)容不亂碼 } } } catch (Exception e) { e.printStackTrace(); } finally { out.close(); } } } |
工具類、服務(wù)器端代碼上面都貼出來了,具體怎么調(diào)用應(yīng)該就不需要說了吧?封裝的已經(jīng)夠清晰明了了
調(diào)用示例DEMO:
1
2
3
4
5
6
7
8
9
10
11
|
//創(chuàng)建HttpClientUtil實(shí)例 HttpClientUtil httpClient = new HttpClientUtil(); MultipartForm form = httpClient. new MultipartForm(); //設(shè)置form屬性、參數(shù) form.setAction( "http://192.168.1.7:8080/UploadFileDemo/cn/com/ajava/servlet/ServletUploadFile" ); File photoFile = new File(sddCardPath+ "//data//me.jpg" ); form.addFileField( "photo" , photoFile); form.addNormalField( "name" , "曾繁添" ); form.addNormalField( "tel" , "15122946685" ); //提交表單 HttpClientUtil.submitForm(form); |
最后說明一下jar問題:
要是android里面應(yīng)用的話,需要注意一下額外引入httpmime-4.3.1.jar(我當(dāng)時(shí)下的這個(gè)是最高版本了),至于fileUpload的jar,直接去apache官網(wǎng)下載吧
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時(shí)也希望多多支持服務(wù)器之家!
原文鏈接:http://www.cnblogs.com/fly100/articles/3492525.html