展会信息港展会大全

Android用http协议上传文件
来源:互联网   发布日期:2015-09-28 16:25:06   浏览:1398次  

导读:Android使用http协议实现文件的上传http协议上传文件一般最大是2M,比较适合上传小于两M的文件[代码] [Java]代码001 import java.io.File;002 import java.io.FileInputStream;003 import java.io.FileNo......

Android使用http协议实现文件的上传

http协议上传文件一般最大是2M,比较适合上传小于两M的文件

[代码] [Java]代码

001 import java.io.File;

002 import java.io.FileInputStream;

003 import java.io.FileNotFoundException;

004 import java.io.InputStream;

005

006 /**

007 * 上传的文件

008 */

009 public class FormFile {

010 /** 上传文件的数据 */

011 private byte[] data;

012 private InputStream inStream;

013 private File file;

014 /** 文件名称 */

015 private String filname;

016 /** 请求参数名称*/

017 private String parameterName;

018 /** 内容类型 */

019 private String contentType = "application/octet-stream";

020 /**

021 *

022 * @param filname 文件名称

023 * @param data 上传的文件数据

024 * @param parameterName 参数

025 * @param contentType 内容类型

026 */

027 public FormFile(String filname, byte[] data, String parameterName, String contentType) {

028 this.data = data;

029 this.filname = filname;

030 this.parameterName = parameterName;

031 if(contentType!=null) this.contentType = contentType;

032 }

033 /**

034 *

035 * @param filname 文件名

036 * @param file 上传的文件

037 * @param parameterName 参数

038 * @param contentType 内容内容类型

039 */

040 public FormFile(String filname, File file, String parameterName, String contentType) {

041 this.filname = filname;

042 this.parameterName = parameterName;

043 this.file = file;

044 try {

045 this.inStream = new FileInputStream(file);

046 } catch (FileNotFoundException e) {

047 e.printStackTrace();

048 }

049 if(contentType!=null) this.contentType = contentType;

050 }

051

052 public File getFile() {

053 return file;

054 }

055

056 public InputStream getInStream() {

057 return inStream;

058 }

059

060 public byte[] getData() {

061 return data;

062 }

063

064 public String getFilname() {

065 return filname;

066 }

067

068 public void setFilname(String filname) {

069 this.filname = filname;

070 }

071

072 public String getParameterName() {

073 return parameterName;

074 }

075

076 public void setParameterName(String parameterName) {

077 this.parameterName = parameterName;

078 }

079

080 public String getContentType() {

081 return contentType;

082 }

083

084 public void setContentType(String contentType) {

085 this.contentType = contentType;

086 }

087

088 }

089

090 /**

091 * 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能:

092 * <FORM METHOD=POST ACTION="http://192.168.0.200:8080/ssi/fileload/test.do" enctype="multipart/form-data">

093 <INPUT TYPE="text" NAME="name">

094 <INPUT TYPE="text" NAME="id">

095 <input type="file" name="imagefile"/>

096 <input type="file" name="zip"/>

097 </FORM>

098 * @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.xxx.cn或http://192.168.1.10:8080这样的路径测试)

099 * @param params 请求参数 key为参数名,value为参数值

100 * @param file 上传文件

101 */

102 public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception{

103 final String BOUNDARY = "---------------------------7da2137580612"; //数据分隔线

104 final String endline = "--" + BOUNDARY + "--\r\n";//数据结束标志

105

106 int fileDataLength = 0;

107 for(FormFile uploadFile : files){//得到文件类型数据的总长度

108 StringBuilder fileExplain = new StringBuilder();

109 fileExplain.append("--");

110 fileExplain.append(BOUNDARY);

111 fileExplain.append("\r\n");

112 fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");

113 fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");

114 fileExplain.append("\r\n");

115 fileDataLength += fileExplain.length();

116 if(uploadFile.getInStream()!=null){

117 fileDataLength += uploadFile.getFile().length();

118 }else{

119 fileDataLength += uploadFile.getData().length;

120 }

121 }

122 StringBuilder textEntity = new StringBuilder();

123 for (Map.Entry<String, String> entry : params.entrySet()) {//构造文本类型参数的实体数据

124 textEntity.append("--");

125 textEntity.append(BOUNDARY);

126 textEntity.append("\r\n");

127 textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");

128 textEntity.append(entry.getValue());

129 textEntity.append("\r\n");

130 }

131 //计算传输给服务器的实体数据总长度

132 int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length;

133

134 URL url = new URL(path);

135 int port = url.getPort()==-1 ? 80 : url.getPort();

136 Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);

137 OutputStream outStream = socket.getOutputStream();

138 //下面完成HTTP请求头的发送

139 String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n";

140 outStream.write(requestmethod.getBytes());

141 String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";

142 outStream.write(accept.getBytes());

143 String language = "Accept-Language: zh-CN\r\n";

144 outStream.write(language.getBytes());

145 String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n";

146 outStream.write(contenttype.getBytes());

147 String contentlength = "Content-Length: "+ dataLength + "\r\n";

148 outStream.write(contentlength.getBytes());

149 String alive = "Connection: Keep-Alive\r\n";

150 outStream.write(alive.getBytes());

151 String host = "Host: "+ url.getHost() +":"+ port +"\r\n";

152 outStream.write(host.getBytes());

153 //写完HTTP请求头后根据HTTP协议再写一个回车换行

154 outStream.write("\r\n".getBytes());

155 //把所有文本类型的实体数据发送出来

156 outStream.write(textEntity.toString().getBytes());

157 //把所有文件类型的实体数据发送出来

158 for(FormFile uploadFile : files){

159 StringBuilder fileEntity = new StringBuilder();

160 fileEntity.append("--");

161 fileEntity.append(BOUNDARY);

162 fileEntity.append("\r\n");

163 fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");

164 fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");

165 outStream.write(fileEntity.toString().getBytes());

166 if(uploadFile.getInStream()!=null){

167 byte[] buffer = new byte[1024];

168 int len = 0;

169 while((len = uploadFile.getInStream().read(buffer, 0,1024))!=-1){

170 outStream.write(buffer, 0, len);

171 }

172 uploadFile.getInStream().close();

173 }else{

174 outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);

175 }

176 outStream.write("\r\n".getBytes());

177 }

178 //下面发送数据结束标志,表示数据已经结束

179 outStream.write(endline.getBytes());

180

181 BufferedReader reader = new BufferedReader(newInputStreamReader(socket.getInputStream()));

182 if(reader.readLine().indexOf("200")==-1){//读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败

183 return false;

184 }

185 outStream.flush();

186 outStream.close();

187 reader.close();

188 socket.close();

189 return true;

190 }

191

192 /**

193 * 提交数据到服务器

194 * @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.xxx.cn或http://192.168.1.10:8080这样的路径测试)

195 * @param params 请求参数 key为参数名,value为参数值

196 * @param file 上传文件

197 */

198 public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception{

199 return post(path, params, new FormFile[]{file});

200 }

赞助本站

人工智能实验室

相关热词: 上传文件 http协议

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港