http请求(二) ---- 文件上传工具
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 public class FormFile {
2 // 上传文件的数据
3 private byte[] data;
4
5 private InputStream inStream;
6
7 // 文件名称
8 private String filename;
9 // 表单名称
10 private String formname;
11 // 内容类型
12 private String contentType = "application/octet-stream";
13
14 public FormFile(String filename, byte[] data, String formname,
15 String contentType) {
16 this.data = data;
17 this.filename = filename;
18 this.formname = formname;
19 if (contentType != null) {
20 this.contentType = contentType;
21 }
22 }
23
24 public FormFile(String filename, InputStream inStream, String formname,
25 String contentType) {
26 this.filename = filename;
27 this.formname = formname;
28 this.inStream = inStream;
29 if (contentType != null) {
30 this.contentType = contentType;
31 }
32 }
33
34 public byte[] getData() {
35 return data;
36 }
37
38 public void setData(byte[] data) {
39 this.data = data;
40 }
41
42 public InputStream getInStream() {
43 return inStream;
44 }
45
46 public void setInStream(InputStream inStream) {
47 this.inStream = inStream;
48 }
49
50 public String getFilename() {
51 return filename;
52 }
53
54 public void setFilename(String filename) {
55 this.filename = filename;
56 }
57
58 public String getFormname() {
59 return formname;
60 }
61
62 public void setFormname(String formname) {
63 this.formname = formname;
64 }
65
66 public String getContentType() {
67 return contentType;
68 }
69
70 public void setContentType(String contentType) {
71 this.contentType = contentType;
72 }
73 }
74
代码
2 // 上传文件的数据
3 private byte[] data;
4
5 private InputStream inStream;
6
7 // 文件名称
8 private String filename;
9 // 表单名称
10 private String formname;
11 // 内容类型
12 private String contentType = "application/octet-stream";
13
14 public FormFile(String filename, byte[] data, String formname,
15 String contentType) {
16 this.data = data;
17 this.filename = filename;
18 this.formname = formname;
19 if (contentType != null) {
20 this.contentType = contentType;
21 }
22 }
23
24 public FormFile(String filename, InputStream inStream, String formname,
25 String contentType) {
26 this.filename = filename;
27 this.formname = formname;
28 this.inStream = inStream;
29 if (contentType != null) {
30 this.contentType = contentType;
31 }
32 }
33
34 public byte[] getData() {
35 return data;
36 }
37
38 public void setData(byte[] data) {
39 this.data = data;
40 }
41
42 public InputStream getInStream() {
43 return inStream;
44 }
45
46 public void setInStream(InputStream inStream) {
47 this.inStream = inStream;
48 }
49
50 public String getFilename() {
51 return filename;
52 }
53
54 public void setFilename(String filename) {
55 this.filename = filename;
56 }
57
58 public String getFormname() {
59 return formname;
60 }
61
62 public void setFormname(String formname) {
63 this.formname = formname;
64 }
65
66 public String getContentType() {
67 return contentType;
68 }
69
70 public void setContentType(String contentType) {
71 this.contentType = contentType;
72 }
73 }
74
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 public class HttpUploadRequester {
2 /**
3 * 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能: <FORM METHOD=POST
4 * ACTION="http://192.168.0.200:8080/ssi/fileload/test.do"
5 * enctype="multipart/form-data"> <INPUT TYPE="text" NAME="name"> <INPUT
6 * TYPE="text" NAME="id"> <input type="file" name="imagefile"/> <input
7 * type="file" name="zip"/> </FORM>
8 *
9 * @param actionUrl
10 * 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,
11 * 你可以使用http://192.168.1.10:8080这样的路径测试)
12 * @param params
13 * 请求参数 key为参数名,value为参数值
14 * @param file
15 * 上传文件
16 */
17 // http协议中分割符,随便定义
18 private static final String HTTP_BOUNDARY = "---------9dx5a2d578c2";
19 private static final String MULTIPART_FORM_DATA = "multipart/form-data";
20 private static final String LINE_ENTER = "\r\n"; // 换行 回车
21 private static final int RESPONSE_OK = 200;
22
23 public static String post(String urlPath, Map<String, String> params,
24 FormFile[] formFiles) {
25 try {
26 URL url = new URL(urlPath);
27 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
28 conn.setRequestMethod("POST");
29 conn.setReadTimeout(5 * 1000);
30 conn.setDoOutput(true); // 发送POST请求, 必须设置允许输出
31 conn.setUseCaches(false);
32 conn.setRequestProperty("Connection", "Keep-Alive"); // 维持长链接
33 conn.setRequestProperty("Charset", "UTF-8");
34 conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA
35 + "; boundary=" + HTTP_BOUNDARY);
36
37 StringBuilder formItemData = new StringBuilder();
38 // 构建 表单字段内容
39 for (Map.Entry<String, String> entry : params.entrySet()) {
40 formItemData.append("--");
41 formItemData.append(HTTP_BOUNDARY);
42 formItemData.append(LINE_ENTER);
43 formItemData.append("Content-Disposition: form-data; name=\""
44 + entry.getKey() + "\"\r\n\r\n");
45 formItemData.append(entry.getValue());
46 formItemData.append(LINE_ENTER);
47 }
48 DataOutputStream outStream = new DataOutputStream(
49 conn.getOutputStream());
50 // 发送表单字段内容到服务器
51 outStream.write(formItemData.toString().getBytes());
52
53 // 发送上传文件数据
54 for (FormFile fileData : formFiles) {
55 StringBuilder fileSplit = new StringBuilder();
56 fileSplit.append("--");
57 fileSplit.append(HTTP_BOUNDARY);
58 fileSplit.append(LINE_ENTER);
59 fileSplit.append("Content-Disposition: form-data;name=\""
60 + fileData.getFormname() + "\";filename=\""
61 + fileData.getFilename() + "\"\r\n");
62 fileSplit.append("Content-Type:" + fileData.getContentType()
63 + LINE_ENTER + LINE_ENTER);
64 outStream.write(fileSplit.toString().getBytes());
65
66 if (fileData.getInStream() != null) {
67 byte[] buffer = new byte[1024];
68 int length = 0;
69 while ((length = fileData.getInStream().read()) != -1) {
70 outStream.write(buffer, 0, length);
71 }
72 fileData.getInStream().close();
73 } else {
74 outStream.write(fileData.getData(), 0,
75 fileData.getData().length);
76 }
77 outStream.write(LINE_ENTER.getBytes());
78 }
79 // 数据结束标志
80 byte[] endData = ("--" + HTTP_BOUNDARY + "--" + LINE_ENTER)
81 .getBytes();
82 outStream.write(endData);
83 outStream.flush();
84 outStream.close();
85 int responseCode = conn.getResponseCode();
86 if (responseCode != RESPONSE_OK) {
87 throw new RuntimeException("请求url失败");
88 }
89 InputStream is = conn.getInputStream();
90 int ch;
91 StringBuilder b = new StringBuilder();
92 while ((ch = is.read()) != -1) {
93 b.append((char) ch);
94 }
95 Log.i("HttpPost", b.toString());
96 conn.disconnect();
97 return b.toString();
98 } catch (Exception e) {
99 throw new RuntimeException();
100 }
101 }
102
103 // 上传单个文件
104 public static String post(String urlPath, Map<String, String> params,
105 FormFile formFiles) {
106 return post(urlPath, params, new FormFile[] { formFiles });
107 }
108 }
109
代码
2 /**
3 * 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能: <FORM METHOD=POST
4 * ACTION="http://192.168.0.200:8080/ssi/fileload/test.do"
5 * enctype="multipart/form-data"> <INPUT TYPE="text" NAME="name"> <INPUT
6 * TYPE="text" NAME="id"> <input type="file" name="imagefile"/> <input
7 * type="file" name="zip"/> </FORM>
8 *
9 * @param actionUrl
10 * 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,
11 * 你可以使用http://192.168.1.10:8080这样的路径测试)
12 * @param params
13 * 请求参数 key为参数名,value为参数值
14 * @param file
15 * 上传文件
16 */
17 // http协议中分割符,随便定义
18 private static final String HTTP_BOUNDARY = "---------9dx5a2d578c2";
19 private static final String MULTIPART_FORM_DATA = "multipart/form-data";
20 private static final String LINE_ENTER = "\r\n"; // 换行 回车
21 private static final int RESPONSE_OK = 200;
22
23 public static String post(String urlPath, Map<String, String> params,
24 FormFile[] formFiles) {
25 try {
26 URL url = new URL(urlPath);
27 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
28 conn.setRequestMethod("POST");
29 conn.setReadTimeout(5 * 1000);
30 conn.setDoOutput(true); // 发送POST请求, 必须设置允许输出
31 conn.setUseCaches(false);
32 conn.setRequestProperty("Connection", "Keep-Alive"); // 维持长链接
33 conn.setRequestProperty("Charset", "UTF-8");
34 conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA
35 + "; boundary=" + HTTP_BOUNDARY);
36
37 StringBuilder formItemData = new StringBuilder();
38 // 构建 表单字段内容
39 for (Map.Entry<String, String> entry : params.entrySet()) {
40 formItemData.append("--");
41 formItemData.append(HTTP_BOUNDARY);
42 formItemData.append(LINE_ENTER);
43 formItemData.append("Content-Disposition: form-data; name=\""
44 + entry.getKey() + "\"\r\n\r\n");
45 formItemData.append(entry.getValue());
46 formItemData.append(LINE_ENTER);
47 }
48 DataOutputStream outStream = new DataOutputStream(
49 conn.getOutputStream());
50 // 发送表单字段内容到服务器
51 outStream.write(formItemData.toString().getBytes());
52
53 // 发送上传文件数据
54 for (FormFile fileData : formFiles) {
55 StringBuilder fileSplit = new StringBuilder();
56 fileSplit.append("--");
57 fileSplit.append(HTTP_BOUNDARY);
58 fileSplit.append(LINE_ENTER);
59 fileSplit.append("Content-Disposition: form-data;name=\""
60 + fileData.getFormname() + "\";filename=\""
61 + fileData.getFilename() + "\"\r\n");
62 fileSplit.append("Content-Type:" + fileData.getContentType()
63 + LINE_ENTER + LINE_ENTER);
64 outStream.write(fileSplit.toString().getBytes());
65
66 if (fileData.getInStream() != null) {
67 byte[] buffer = new byte[1024];
68 int length = 0;
69 while ((length = fileData.getInStream().read()) != -1) {
70 outStream.write(buffer, 0, length);
71 }
72 fileData.getInStream().close();
73 } else {
74 outStream.write(fileData.getData(), 0,
75 fileData.getData().length);
76 }
77 outStream.write(LINE_ENTER.getBytes());
78 }
79 // 数据结束标志
80 byte[] endData = ("--" + HTTP_BOUNDARY + "--" + LINE_ENTER)
81 .getBytes();
82 outStream.write(endData);
83 outStream.flush();
84 outStream.close();
85 int responseCode = conn.getResponseCode();
86 if (responseCode != RESPONSE_OK) {
87 throw new RuntimeException("请求url失败");
88 }
89 InputStream is = conn.getInputStream();
90 int ch;
91 StringBuilder b = new StringBuilder();
92 while ((ch = is.read()) != -1) {
93 b.append((char) ch);
94 }
95 Log.i("HttpPost", b.toString());
96 conn.disconnect();
97 return b.toString();
98 } catch (Exception e) {
99 throw new RuntimeException();
100 }
101 }
102
103 // 上传单个文件
104 public static String post(String urlPath, Map<String, String> params,
105 FormFile formFiles) {
106 return post(urlPath, params, new FormFile[] { formFiles });
107 }
108 }
109
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 // 以表单方式发送请求
2
3 public static void sendDataToServerByForm() throws Exception {
4
5 Map<String, String> params = new HashMap<String, String>();
6
7 params.put("method", "sendDataByForm");
8
9 params.put("strData", "字符串数据");
10
11 // 获取SDCard中的good.jpg
12
13 File file = new File(Environment.getExternalStorageDirectory(),
14
15 "app_Goog_Android_w.png");
16
17 FormFile fileData = new FormFile("app_Goog_Android_w.png", new FileInputStream(file),
18
19 "fileData", "application/octet-stream");
20
21 HttpUploadRequester.post(
22
23 "http://192.168.0.2:8080/AndroidWebServer/server.do", params,
24
25 fileData);
26
27 }
2
3 public static void sendDataToServerByForm() throws Exception {
4
5 Map<String, String> params = new HashMap<String, String>();
6
7 params.put("method", "sendDataByForm");
8
9 params.put("strData", "字符串数据");
10
11 // 获取SDCard中的good.jpg
12
13 File file = new File(Environment.getExternalStorageDirectory(),
14
15 "app_Goog_Android_w.png");
16
17 FormFile fileData = new FormFile("app_Goog_Android_w.png", new FileInputStream(file),
18
19 "fileData", "application/octet-stream");
20
21 HttpUploadRequester.post(
22
23 "http://192.168.0.2:8080/AndroidWebServer/server.do", params,
24
25 fileData);
26
27 }