Android中发送Http请求实例(包括文件上传、servlet接收)
2012-02-11 12:09
447 查看
前天开始要准备实现手机端往服务器传参数,还要能传附件,找了不少文章和资料,现在总结一下分享分享:代码中的catch什么的就省略了,尝试了图片、txt、xml是没问题的.. 各位 尽情拍砖吧。
发完发现代码部分的格式……这个编辑器不太会用,怎么感觉把换行都去掉了,处理好换行缩进也……
首先我是写了个java工程测试发送post请求:可以包含文本参数和文件参数****************************************************
1 /**
2 * 通过http协议提交数据到服务端,实现表单提交功能,包括上传文件
3 * @param actionUrl 上传路径
4 * @param params 请求参数 key为参数名,value为参数值
5 * @param file 上传文件
6 */
7 public static void postMultiParams(String actionUrl, Map<String, String> params, FormBean[] files) {
8 try {
9 PostMethod post = new PostMethod(actionUrl);
10 List<art> formParams = new ArrayList<art>();
11 for(Map.Entry<String, String> entry : params.entrySet()){
12 formParams.add(new StringPart(entry.getKey(), entry.getValue()));
13 }
14
15 if(files!=null)
16 for(FormBean file : files){
17 //filename为在服务端接收时希望保存成的文件名,filepath是本地文件路径(包括了源文件名),filebean中就包含了这俩属性
18 formParams.add(new FilePart("file", file.getFilename(), new File(file.getFilepath())));
19 }
20
21 Part[] parts = new Part[formParams.size()];
22 Iterator<art> pit = formParams.iterator();
23 int i=0;
24
25 while(pit.hasNext()){
26 parts[i++] = pit.next();
27 }
28 //如果出现乱码可以尝试一下方式
29 //StringPart sp = new StringPart("TEXT", "testValue", "GB2312");
30 //FilePart fp = new FilePart("file", "test.txt", new File("./temp/test.txt"), null, "GB2312"
31 //postMethod.getParams().setContentCharset("GB2312");
32
33 MultipartRequestEntity mrp = new MultipartRequestEntity(parts, post.getParams());
34 post.setRequestEntity(mrp);
35
36 //execute post method
37 HttpClient client = new HttpClient();
38 int code = client.executeMethod(post);
39 System.out.println(code);
40 } catch ...
41 }
复制代码
通过以上代码可以成功的模拟java客户端发送post请求,服务端也能接收并保存文件
java端测试的main方法:
42 public static void main(String[] args){
43 String actionUrl = "http://192.168.0.123:8080/WSserver/androidUploadServlet";
44 Map<String, String> strParams = new HashMap<String, String>();
45 strParams.put("paramOne", "valueOne");
46 strParams.put("paramTwo", "valueTwo");
47 FormBean[] files = new FormBean[]{new FormBean("dest1.xml", "F:/testpostsrc/main.xml")};
48 HttpTool.postMultiParams(actionUrl,strParams,files);
49 }
复制代码
本以为大功告成了,结果一移植到android工程中,编译是没有问题的。
但是运行时抛了异常 先是说找不到PostMethod类,org.apache.commons.httpclient.methods.PostMethod这个类绝对是有包含的;
还有个异常就是VerifyError。 开发中有几次碰到这个异常都束手无策,觉得是SDK不兼容还是怎么地,哪位知道可得跟我说说~~
于是看网上有直接分析http request的内容构建post请求的,也有找到带上传文件的,拿下来运行老是有些问题,便直接通过运行上面的java工程发送的post请求,在servlet中打印出请求内容,然后对照着拼接字符串和流终于给实现了!代码如下:
***********************************************************
50 /**
51 * 通过拼接的方式构造请求内容,实现参数传输以及文件传输
52 * @param actionUrl
53 * @param params
54 * @param files
55 * @return
56 * @throws IOException
57 */
58 public static String post(String actionUrl, Map<String, String> params,
59 Map<String, File> files) throws IOException {
60
61 String BOUNDARY = java.util.UUID.randomUUID().toString();
62 String PREFIX = "--" , LINEND = "\r\n";
63 String MULTIPART_FROM_DATA = "multipart/form-data";
64 String CHARSET = "UTF-8";
65
66 URL uri = new URL(actionUrl);
67 HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
68 conn.setReadTimeout(5 * 1000); // 缓存的最长时间
69 conn.setDoInput(true);// 允许输入
70 conn.setDoOutput(true);// 允许输出
71 conn.setUseCaches(false); // 不允许使用缓存
72 conn.setRequestMethod("POST");
73 conn.setRequestProperty("connection", "keep-alive");
74 conn.setRequestProperty("Charsert", "UTF-8");
75 conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
76
77 // 首先组拼文本类型的参数
78 StringBuilder sb = new StringBuilder();
79 for (Map.Entry<String, String> entry : params.entrySet()) {
80 sb.append(PREFIX);
81 sb.append(BOUNDARY);
82 sb.append(LINEND);
83 sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
84 sb.append("Content-Type: text/plain; charset=" + CHARSET+LINEND);
85 sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
86 sb.append(LINEND);
87 sb.append(entry.getValue());
88 sb.append(LINEND);
89 }
90
91 DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
92 outStream.write(sb.toString().getBytes());
93 // 发送文件数据
94 if(files!=null)
95 for (Map.Entry<String, File> file: files.entrySet()) {
96 StringBuilder sb1 = new StringBuilder();
97 sb1.append(PREFIX);
98 sb1.append(BOUNDARY);
99 sb1.append(LINEND);
100 sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""+file.getKey()+"\""+LINEND);
101 sb1.append("Content-Type: application/octet-stream; charset="+CHARSET+LINEND);
102 sb1.append(LINEND);
103 outStream.write(sb1.toString().getBytes());
104
105 InputStream is = new FileInputStream(file.getValue());
106 byte[] buffer = new byte[1024];
107 int len = 0;
108 while ((len = is.read(buffer)) != -1) {
109 outStream.write(buffer, 0, len);
110 }
111
112 is.close();
113 outStream.write(LINEND.getBytes());
114 }
115
116 //请求结束标志
117 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
118 outStream.write(end_data);
119 outStream.flush();
120 // 得到响应码
121 int res = conn.getResponseCode();
122 if (res == 200) {
123 InputStream in = conn.getInputStream();
124 int ch;
125 StringBuilder sb2 = new StringBuilder();
126 while ((ch = in.read()) != -1) {
127 sb2.append((char) ch);
128 }
129 }
130 outStream.close();
131 conn.disconnect();
132 return in.toString();
133 }
复制代码
**********************
button响应中的代码:
**********************
134 public void onClick(View v){
135 String actionUrl = getApplicationContext().getString(R.string.wtsb_req_upload);
136 Map<String, String> params = new HashMap<String, String>();
137 params.put("strParamName", "strParamValue");
138 Map<String, File> files = new HashMap<String, File>();
139 files.put("tempAndroid.txt", new File("/sdcard/temp.txt"));
140 try {
141 HttpTool.postMultiParams(actionUrl, params, files);
142 } catch ...
复制代码
***************************
服务器端servlet代码:
***************************
143 public void doPost(HttpServletRequest request, HttpServletResponse response)
144 throws ServletException, IOException {
145
146 //print request.getInputStream to check request content
147 //HttpTool.printStreamContent(request.getInputStream());
148
149 RequestContext req = new ServletRequestContext(request);
150 if(FileUpload.isMultipartContent(req)){
151 DiskFileItemFactory factory = new DiskFileItemFactory();
152 ServletFileUpload fileUpload = new ServletFileUpload(factory);
153 fileUpload.setFileSizeMax(FILE_MAX_SIZE);
154
155 List items = new ArrayList();
156 try {
157 items = fileUpload.parseRequest(request);
158 } catch ...
159
160 Iterator it = items.iterator();
161 while(it.hasNext()){
162 FileItem fileItem = (FileItem)it.next();
163 if(fileItem.isFormField()){
164 System.out.println(fileItem.getFieldName()+" "+fileItem.getName()+" "+new String(fileItem.getString().getBytes("ISO-8859-1"),"GBK"));
165 } else {
166 System.out.println(fileItem.getFieldName()+" "+fileItem.getName()+" "+
167 fileItem.isInMemory()+" "+fileItem.getContentType()+" "+fileItem.getSize());
168 if(fileItem.getName()!=null && fileItem.getSize()!=0){
169 File fullFile = new File(fileItem.getName());
170 File newFile = new File(FILE_SAVE_PATH+fullFile.getName());
171 try {
172 fileItem.write(newFile);
173 } catch ...
174 } else {
175 System.out.println("no file choosen or empty file");
176 }
177 }
178 }
179 }
180 }
181
182 public void init() throws ServletException {
183 //读取在web.xml中配置的init-param
184 FILE_MAX_SIZE = Long.parseLong(this.getInitParameter("file_max_size"));//上传文件大小限制
185 FILE_SAVE_PATH = this.getInitParameter("file_save_path");//文件保存位置
186 }
发完发现代码部分的格式……这个编辑器不太会用,怎么感觉把换行都去掉了,处理好换行缩进也……
首先我是写了个java工程测试发送post请求:可以包含文本参数和文件参数****************************************************
1 /**
2 * 通过http协议提交数据到服务端,实现表单提交功能,包括上传文件
3 * @param actionUrl 上传路径
4 * @param params 请求参数 key为参数名,value为参数值
5 * @param file 上传文件
6 */
7 public static void postMultiParams(String actionUrl, Map<String, String> params, FormBean[] files) {
8 try {
9 PostMethod post = new PostMethod(actionUrl);
10 List<art> formParams = new ArrayList<art>();
11 for(Map.Entry<String, String> entry : params.entrySet()){
12 formParams.add(new StringPart(entry.getKey(), entry.getValue()));
13 }
14
15 if(files!=null)
16 for(FormBean file : files){
17 //filename为在服务端接收时希望保存成的文件名,filepath是本地文件路径(包括了源文件名),filebean中就包含了这俩属性
18 formParams.add(new FilePart("file", file.getFilename(), new File(file.getFilepath())));
19 }
20
21 Part[] parts = new Part[formParams.size()];
22 Iterator<art> pit = formParams.iterator();
23 int i=0;
24
25 while(pit.hasNext()){
26 parts[i++] = pit.next();
27 }
28 //如果出现乱码可以尝试一下方式
29 //StringPart sp = new StringPart("TEXT", "testValue", "GB2312");
30 //FilePart fp = new FilePart("file", "test.txt", new File("./temp/test.txt"), null, "GB2312"
31 //postMethod.getParams().setContentCharset("GB2312");
32
33 MultipartRequestEntity mrp = new MultipartRequestEntity(parts, post.getParams());
34 post.setRequestEntity(mrp);
35
36 //execute post method
37 HttpClient client = new HttpClient();
38 int code = client.executeMethod(post);
39 System.out.println(code);
40 } catch ...
41 }
复制代码
通过以上代码可以成功的模拟java客户端发送post请求,服务端也能接收并保存文件
java端测试的main方法:
42 public static void main(String[] args){
43 String actionUrl = "http://192.168.0.123:8080/WSserver/androidUploadServlet";
44 Map<String, String> strParams = new HashMap<String, String>();
45 strParams.put("paramOne", "valueOne");
46 strParams.put("paramTwo", "valueTwo");
47 FormBean[] files = new FormBean[]{new FormBean("dest1.xml", "F:/testpostsrc/main.xml")};
48 HttpTool.postMultiParams(actionUrl,strParams,files);
49 }
复制代码
本以为大功告成了,结果一移植到android工程中,编译是没有问题的。
但是运行时抛了异常 先是说找不到PostMethod类,org.apache.commons.httpclient.methods.PostMethod这个类绝对是有包含的;
还有个异常就是VerifyError。 开发中有几次碰到这个异常都束手无策,觉得是SDK不兼容还是怎么地,哪位知道可得跟我说说~~
于是看网上有直接分析http request的内容构建post请求的,也有找到带上传文件的,拿下来运行老是有些问题,便直接通过运行上面的java工程发送的post请求,在servlet中打印出请求内容,然后对照着拼接字符串和流终于给实现了!代码如下:
***********************************************************
50 /**
51 * 通过拼接的方式构造请求内容,实现参数传输以及文件传输
52 * @param actionUrl
53 * @param params
54 * @param files
55 * @return
56 * @throws IOException
57 */
58 public static String post(String actionUrl, Map<String, String> params,
59 Map<String, File> files) throws IOException {
60
61 String BOUNDARY = java.util.UUID.randomUUID().toString();
62 String PREFIX = "--" , LINEND = "\r\n";
63 String MULTIPART_FROM_DATA = "multipart/form-data";
64 String CHARSET = "UTF-8";
65
66 URL uri = new URL(actionUrl);
67 HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
68 conn.setReadTimeout(5 * 1000); // 缓存的最长时间
69 conn.setDoInput(true);// 允许输入
70 conn.setDoOutput(true);// 允许输出
71 conn.setUseCaches(false); // 不允许使用缓存
72 conn.setRequestMethod("POST");
73 conn.setRequestProperty("connection", "keep-alive");
74 conn.setRequestProperty("Charsert", "UTF-8");
75 conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
76
77 // 首先组拼文本类型的参数
78 StringBuilder sb = new StringBuilder();
79 for (Map.Entry<String, String> entry : params.entrySet()) {
80 sb.append(PREFIX);
81 sb.append(BOUNDARY);
82 sb.append(LINEND);
83 sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
84 sb.append("Content-Type: text/plain; charset=" + CHARSET+LINEND);
85 sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
86 sb.append(LINEND);
87 sb.append(entry.getValue());
88 sb.append(LINEND);
89 }
90
91 DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
92 outStream.write(sb.toString().getBytes());
93 // 发送文件数据
94 if(files!=null)
95 for (Map.Entry<String, File> file: files.entrySet()) {
96 StringBuilder sb1 = new StringBuilder();
97 sb1.append(PREFIX);
98 sb1.append(BOUNDARY);
99 sb1.append(LINEND);
100 sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""+file.getKey()+"\""+LINEND);
101 sb1.append("Content-Type: application/octet-stream; charset="+CHARSET+LINEND);
102 sb1.append(LINEND);
103 outStream.write(sb1.toString().getBytes());
104
105 InputStream is = new FileInputStream(file.getValue());
106 byte[] buffer = new byte[1024];
107 int len = 0;
108 while ((len = is.read(buffer)) != -1) {
109 outStream.write(buffer, 0, len);
110 }
111
112 is.close();
113 outStream.write(LINEND.getBytes());
114 }
115
116 //请求结束标志
117 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
118 outStream.write(end_data);
119 outStream.flush();
120 // 得到响应码
121 int res = conn.getResponseCode();
122 if (res == 200) {
123 InputStream in = conn.getInputStream();
124 int ch;
125 StringBuilder sb2 = new StringBuilder();
126 while ((ch = in.read()) != -1) {
127 sb2.append((char) ch);
128 }
129 }
130 outStream.close();
131 conn.disconnect();
132 return in.toString();
133 }
复制代码
**********************
button响应中的代码:
**********************
134 public void onClick(View v){
135 String actionUrl = getApplicationContext().getString(R.string.wtsb_req_upload);
136 Map<String, String> params = new HashMap<String, String>();
137 params.put("strParamName", "strParamValue");
138 Map<String, File> files = new HashMap<String, File>();
139 files.put("tempAndroid.txt", new File("/sdcard/temp.txt"));
140 try {
141 HttpTool.postMultiParams(actionUrl, params, files);
142 } catch ...
复制代码
***************************
服务器端servlet代码:
***************************
143 public void doPost(HttpServletRequest request, HttpServletResponse response)
144 throws ServletException, IOException {
145
146 //print request.getInputStream to check request content
147 //HttpTool.printStreamContent(request.getInputStream());
148
149 RequestContext req = new ServletRequestContext(request);
150 if(FileUpload.isMultipartContent(req)){
151 DiskFileItemFactory factory = new DiskFileItemFactory();
152 ServletFileUpload fileUpload = new ServletFileUpload(factory);
153 fileUpload.setFileSizeMax(FILE_MAX_SIZE);
154
155 List items = new ArrayList();
156 try {
157 items = fileUpload.parseRequest(request);
158 } catch ...
159
160 Iterator it = items.iterator();
161 while(it.hasNext()){
162 FileItem fileItem = (FileItem)it.next();
163 if(fileItem.isFormField()){
164 System.out.println(fileItem.getFieldName()+" "+fileItem.getName()+" "+new String(fileItem.getString().getBytes("ISO-8859-1"),"GBK"));
165 } else {
166 System.out.println(fileItem.getFieldName()+" "+fileItem.getName()+" "+
167 fileItem.isInMemory()+" "+fileItem.getContentType()+" "+fileItem.getSize());
168 if(fileItem.getName()!=null && fileItem.getSize()!=0){
169 File fullFile = new File(fileItem.getName());
170 File newFile = new File(FILE_SAVE_PATH+fullFile.getName());
171 try {
172 fileItem.write(newFile);
173 } catch ...
174 } else {
175 System.out.println("no file choosen or empty file");
176 }
177 }
178 }
179 }
180 }
181
182 public void init() throws ServletException {
183 //读取在web.xml中配置的init-param
184 FILE_MAX_SIZE = Long.parseLong(this.getInitParameter("file_max_size"));//上传文件大小限制
185 FILE_SAVE_PATH = this.getInitParameter("file_save_path");//文件保存位置
186 }
相关文章推荐
- Android中发送Http请求实例(包括文件上传、servlet接收)
- Android中发送Http请求(包括文件上传、servlet接收)的实例代码
- zz:Android中发送Http请求实例(包括文件上传、servlet接收)
- zz:Android中发送Http请求实例(包括文件上传、servlet接收)
- Android中发送Http请求(包括文件上传、servlet接收)的实例代码
- Android中发送Http请求实例(包括文件上传、servlet接收)
- Android中发送Http请求实例(包括文件上传、servlet接收)
- Android之Http请求实例(文件上传+servlet接收)
- android 批量上传图片+Servlet接收文件
- Android中的webview支持页面中的文件上传实例代码
- HttpClient发送http请求以及上传文件
- Android 发送HTTP GET POST 请求以及通过 MultipartEntityBuilder 上传文件
- Android 上传文件,图片。以及服务器端接收相关
- Android和FTP服务器交互,上传下载文件(实例demo)
- VC++ 用WinInet发送HTTP请求和上传文件
- android批量文件上传(服务器采用servlet处理)
- Java后台模拟向Servlet发送POST文件上传请求(转载)
- android通过servlet上传文件到服务器
- Android中使用又拍云存储来上传文件(包括图片、音频和视频等)
- SpringMVC中使用StandardServletMultipartResolver上传文件实例