Android之使用Http协议实现文件上传功能.docx

上传人:b****4 文档编号:4884524 上传时间:2022-12-11 格式:DOCX 页数:16 大小:21.94KB
下载 相关 举报
Android之使用Http协议实现文件上传功能.docx_第1页
第1页 / 共16页
Android之使用Http协议实现文件上传功能.docx_第2页
第2页 / 共16页
Android之使用Http协议实现文件上传功能.docx_第3页
第3页 / 共16页
Android之使用Http协议实现文件上传功能.docx_第4页
第4页 / 共16页
Android之使用Http协议实现文件上传功能.docx_第5页
第5页 / 共16页
点击查看更多>>
下载资源
资源描述

Android之使用Http协议实现文件上传功能.docx

《Android之使用Http协议实现文件上传功能.docx》由会员分享,可在线阅读,更多相关《Android之使用Http协议实现文件上传功能.docx(16页珍藏版)》请在冰豆网上搜索。

Android之使用Http协议实现文件上传功能.docx

Android之使用Http协议实现文件上传功能

注意一般使用Http协议上传的文件都比较小,一般是小于2M

这里示例是上传一个小的MP3文件

1.主Activity:

MainActivity.java

1publicclassMainActivityextendsActivity

2{

3privatestaticfinalStringTAG="MainActivity";

4privateEditTexttimelengthText;

5privateEditTexttitleText;

6privateEditTextvideoText;

7

8@Override

9publicvoidonCreate(BundlesavedInstanceState)

10{

11super.onCreate(savedInstanceState);

12setContentView(R.layout.main);

13//提交上传按钮

14Buttonbutton=(Button)this.findViewById(R.id.button);

15timelengthText=(EditText)this.findViewById(R.id.timelength);

16videoText=(EditText)this.findViewById(R.id.video);

17titleText=(EditText)this.findViewById(R.id.title);

18button.setOnClickListener(newView.OnClickListener()

19{

20@Override

21publicvoidonClick(Viewv)

22{

23Stringtitle=titleText.getText().toString();

24Stringtimelength=timelengthText.getText().toString();

25Mapparams=newHashMap();

26params.put("method","save");

27params.put("title",title);

28params.put("timelength",timelength);

29try

30{

31//得到SDCard的目录

32FileuploadFile=newFile(Environment.getExternalStorageDirectory(),videoText.getText().toString());

33//上传音频文件

34FormFileformfile=newFormFile("02.mp3",uploadFile,"video","audio/mpeg");

35SocketHttpRequester.post("http:

//192.168.1.100:

8080/videoweb/video/manage.do",params,formfile);

36Toast.makeText(MainActivity.this,R.string.success,1).show();

37}

38catch(Exceptione)

39{

40Toast.makeText(MainActivity.this,R.string.error,1).show();

41Log.e(TAG,e.toString());

42}

43}

44});

45}

46}

2.上传工具类,注意里面构造协议字符串需要根据不同的提交表单来处理

47publicclassSocketHttpRequester

48{

49/**

50*发送xml数据

51*@parampath请求地址

52*@paramxmlxml数据

53*@paramencoding编码

54*@return

55*@throwsException

56*/

57publicstaticbyte[]postXml(Stringpath,Stringxml,Stringencoding)throwsException{

58byte[]data=xml.getBytes(encoding);

59URLurl=newURL(path);

60HttpURLConnectionconn=(HttpURLConnection)url.openConnection();

61conn.setRequestMethod("POST");

62conn.setDoOutput(true);

63//baidu

64conn.setRequestProperty("Content-Type","text/xml;charset="+encoding);

65conn.setRequestProperty("Content-Length",String.valueOf(data.length));

66

67conn.setConnectTimeout(5*1000);

68OutputStreamoutStream=conn.getOutputStream();

69outStream.write(data);

70outStream.flush();

71outStream.close();

72if(conn.getResponseCode()==200){

73returnreadStream(conn.getInputStream());

74}

75returnnull;

76}

77

78/**

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

80*

//192.168.0.200:

8080/ssi/fileload/test.do"enctype="multipart/form-data">

81

82

83

84

85

86*@parampath上传路径(注:

避免使用localhost或127.0.0.1这样的路径测试,

87*因为它会指向手机模拟器,你可以使用或http:

//192.168.1.10:

8080这样的路径测试)

88*@paramparams请求参数key为参数名,value为参数值

89*@paramfile上传文件

90*/

91publicstaticbooleanpost(Stringpath,Mapparams,FormFile[]files)throwsException

92{

93//数据分隔线

94finalStringBOUNDARY="---------------------------7da2137580612";

95//数据结束标志"---------------------------7da2137580612--"

96finalStringendline="--"+BOUNDARY+"--/r/n";

97

98//下面两个for循环都是为了得到数据长度参数,依据表单的类型而定

99//首先得到文件类型数据的总长度(包括文件分割线)

100intfileDataLength=0;

101for(FormFileuploadFile:

files)

102{

103StringBuilderfileExplain=newStringBuilder();

104fileExplain.append("--");

105fileExplain.append(BOUNDARY);

106fileExplain.append("/r/n");

107fileExplain.append("Content-Disposition:

form-data;name=/""+uploadFile.getParameterName()+"/";filename=/""+uploadFile.getFilname()+"/"/r/n");

108fileExplain.append("Content-Type:

"+uploadFile.getContentType()+"/r/n/r/n");

109fileExplain.append("/r/n");

110fileDataLength+=fileExplain.length();

111if(uploadFile.getInStream()!

=null){

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

113}else{

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

115}

116}

117//再构造文本类型参数的实体数据

118StringBuildertextEntity=newStringBuilder();

119for(Map.Entryentry:

params.entrySet())

120{

121textEntity.append("--");

122textEntity.append(BOUNDARY);

123textEntity.append("/r/n");

124textEntity.append("Content-Disposition:

form-data;name=/""+entry.getKey()+"/"/r/n/r/n");

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

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

127}

128

129//计算传输给服务器的实体数据总长度(文本总长度+数据总长度+分隔符)

130intdataLength=textEntity.toString().getBytes().length+fileDataLength+endline.getBytes().length;

131

132URLurl=newURL(path);

133//默认端口号其实可以不写

134intport=url.getPort()==-1?

80:

url.getPort();

135//建立一个Socket链接

136Socketsocket=newSocket(InetAddress.getByName(url.getHost()),port);

137//获得一个输出流(从Android流到web)

138OutputStreamoutStream=socket.getOutputStream();

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

140Stringrequestmethod="POST"+url.getPath()+"HTTP/1.1/r/n";

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

142//构建accept

143Stringaccept="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";

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

145//构建language

146Stringlanguage="Accept-Language:

zh-CN/r/n";

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

148//构建contenttype

149Stringcontenttype="Content-Type:

multipart/form-data;boundary="+BOUNDARY+"/r/n";

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

151//构建contentlength

152Stringcontentlength="Content-Length:

"+dataLength+"/r/n";

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

154//构建alive

155Stringalive="Connection:

Keep-Alive/r/n";

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

157//构建host

158Stringhost="Host:

"+url.getHost()+":

"+port+"/r/n";

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

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

161outStream.write("/r/n".getBytes());

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

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

164

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

166for(FormFileuploadFile:

files)

167{

168StringBuilderfileEntity=newStringBuilder();

169fileEntity.append("--");

170fileEntity.append(BOUNDARY);

171fileEntity.append("/r/n");

172fileEntity.append("Content-Disposition:

form-data;name=/""+uploadFile.getParameterName()+"/";filename=/""+uploadFile.getFilname()+"/"/r/n");

173fileEntity.append("Content-Type:

"+uploadFile.getContentType()+"/r/n/r/n");

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

175//边读边写

176if(uploadFile.getInStream()!

=null)

177{

178byte[]buffer=newbyte[1024];

179intlen=0;

180while((len=uploadFile.getInStream().read(buffer,0,1024))!

=-1)

181{

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

183}

184uploadFile.getInStream().close();

185}

186else

187{

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

189}

190outStream.write("/r/n".getBytes());

191}

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

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

194BufferedReaderreader=newBufferedReader(newInputStreamReader(socket.getInputStream()));

195//读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败

196if(reader.readLine().indexOf("200")==-1)

197{

198returnfalse;

199}

200outStream.flush();

201outStream.close();

202reader.close();

203socket.close();

204returntrue;

205}

206

207/**

208*提交数据到服务器

209*@parampath上传路径(注:

避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用或http:

//192.168.1.10:

8080这样的路径测试)

210*@paramparams请求参数key为参数名,value为参数值

211*@paramfile上传文件

212*/

213publicstaticbooleanpost(Stringpath,Mapparams,FormFilefile)throwsException

214{

215returnpost(path,params,newFormFile[]{file});

216}

217/**

218*提交数据到服务器

219*@parampath上传路径(注:

避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用或http:

//192.168.1.10:

8080这样的路径测试)

220*@paramparams请求参数key为参数名,value为参数值

221*@paramencode编码

222*/

223publicstaticbyte[]postFromHttpClient(Stringpath,Mapparams,Stringencode)throwsException

224{

225//用于存放请求参数

226Listformparams=newArrayList();

227for(Map.Entryentry:

params.entrySet())

228{

229formparams.add(newBasicNameValuePair(entry.getKey(),entry.getValue()));

230}

231UrlEncodedFormEntityentity=newUrlEncodedFormEntity(formparams,encode);

232HttpPosthttppost=newHttpPost(path);

233httppost.setEntity(entity);

234//看作是浏览器

235HttpClienthttpclient=newDefaultHttpClient();

236//发送post请求

237HttpResponseresponse=httpclient.execute(httppost);

238returnreadStream(response.getEntity().getContent());

239}

240/**

241*发送请求

242*@parampath请求路径

243*@paramparams请求参数key为参数名称value为参数值

244*@paramencode请求参数的编码

245*/

246publicstaticbyte[]post(Stringpath,Mapparams,Stringencode)throwsException

247{

248//Stringparams="method=save&name="+URLEncoder.encode("老毕","UTF-8")+"&age=28&";//需要发送的参数

249StringBuilderparambuilder=

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 求职职场 > 简历

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1