您的位置:首页 > 理论基础 > 计算机网络

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

2011-11-06 11:42 666 查看
import
java.io.File;
002
import
java.io.FileInputStream;
004
import
java.io.InputStream;

003
import
java.io.FileNotFoundException;
05
006
/**
007
*上传的文件
008
*/
009
public
class
FormFile{
010
/**上传文件的数据*/
011
private
byte
[]data;
012
private

InputStreaminStream;
013
private

Filefile;
014
/**文件名称*/
015
private

Stringfilname;
016
/**请求参数名称*/
017
private

StringparameterName;
018
/**内容类型*/
019
private

StringcontentType=
"application/octet-stream"
;
020
/**
021
*
022
*@paramfilname文件名称
023
*@paramdata上传的文件数据
024
*@paramparameterName参数
025
*@paramcontentType内容类型
026
*/
027
public

FormFile(Stringfilname,
byte
[]data,StringparameterName,StringcontentType){
028
this
.data=data;
029
this
.filname=filname;
030
this
.parameterName=parameterName;
031
if
(contentType!=
null
)
this
.contentType=contentType;
032
}
033
/**
034
*
035
*@paramfilname文件名
036
*@paramfile上传的文件
037
*@paramparameterName参数
038
*@paramcontentType内容内容类型
039
*/
040
public

FormFile(Stringfilname,Filefile,StringparameterName,StringcontentType){
041
this
.filname=filname;
042
this
.parameterName=parameterName;
043
this
.file=file;
044
try

{
045
this
.inStream=
new
FileInputStream(file);
046
}

catch
(FileNotFoundExceptione){
047
e.printStackTrace();
048
}

049
if
(contentType!=
null
)
this
.contentType=contentType;
050
}
051
052
public

FilegetFile(){
053
return

file;
054
}
055
056
public

InputStreamgetInStream(){
057
return

inStream;
058
}
059
060
public
byte
[]getData(){
061
return

data;
062
}
063
064
public

StringgetFilname(){
065
return

filname;
066
}
067
068
public
void
setFilname(Stringfilname){
069
this
.filname=filname;
070
}
071
072
public

StringgetParameterName(){
073
return

parameterName;
074
}
075
076
public
void
setParameterName(StringparameterName){

077
this
.parameterName=parameterName;
078
}
079
080
public

StringgetContentType(){
081
return

contentType;
082
}
083
084
public
void
setContentType(StringcontentType){

085
this
.contentType=contentType;
086
}
087
088
}
089
090
/**
091
*直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能:
092
*<FORMMETHOD=POSTACTION="http://192.168.0.200:8080/ssi/fileload/test.do"enctype="multipart/form-data">
093
<INPUTTYPE="text"NAME="name">
094
<INPUTTYPE="text"NAME="id">
095
<inputtype="file"name="imagefile"/>
096
<inputtype="file"name="zip"/>
097
</FORM>
098
*@parampath上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.xxx.cn或http://192.168.1.10:8080这样的路径测试)
099
*@paramparams请求参数key为参数名,value为参数值
100
*@paramfile上传文件
101
*/
102
public
static
boolean

post(Stringpath,Map<String,String>params,FormFile[]files)
throws

Exception{
103
final

StringBOUNDARY=
"---------------------------7da2137580612"
;
//数据分隔线
104
final

Stringendline=
"--"

+BOUNDARY+
"--\r\n"
;
//数据结束标志
105
106
int

fileDataLength=
0
;
107
for
(FormFileuploadFile:files){
//得到文件类型数据的总长度
108
StringBuilderfileExplain=
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
StringBuildertextEntity=
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
URLurl=
new
URL(path);
135
int

port=url.getPort()==-
1

?
80

:url.getPort();
136
Socketsocket=
new
Socket(InetAddress.getByName(url.getHost()),port);
137
OutputStreamoutStream=socket.getOutputStream();
138
//下面完成HTTP请求头的发送
139
Stringrequestmethod=
"POST"
+url.getPath()+
"HTTP/1.1\r\n"
;
140
outStream.write(requestmethod.getBytes());
141
Stringaccept=
"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
Stringlanguage=
"Accept-Language:zh-CN\r\n"
;
144
outStream.write(language.getBytes());
145
Stringcontenttype=
"Content-Type:multipart/form-data;boundary="
+BOUNDARY+
"\r\n"
;

146
outStream.write(contenttype.getBytes());
147
Stringcontentlength=
"Content-Length:"
+dataLength+
"\r\n"
;

148
outStream.write(contentlength.getBytes());
149
Stringalive=
"Connection:Keep-Alive\r\n"
;
150
outStream.write(alive.getBytes());
151
Stringhost=
"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
(FormFileuploadFile:files){
159
StringBuilderfileEntity=
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
BufferedReaderreader=
new
BufferedReader(
new

InputStreamReader(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
*@parampath上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.xxx.cn或http://192.168.1.10:8080这样的路径测试)
195
*@paramparams请求参数key为参数名,value为参数值
196
*@paramfile上传文件
197
*/
198
public
static
boolean

post(Stringpath,Map<String,String>params,FormFilefile)
throws

Exception{
199
return

post(path,params,
new

FormFile[]{file});
200
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: