android之网络文件上传下载源码_第1页
android之网络文件上传下载源码_第2页
android之网络文件上传下载源码_第3页
android之网络文件上传下载源码_第4页
android之网络文件上传下载源码_第5页
已阅读5页,还剩7页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、android 之网络文件上传下载源码01:54AMLinearLayoutxmlns:android=http: SD 卡目录publicFileUtils()SDPATH=Environment.getExternalStorageDirectory()+/;System.out.println(sdcardsdirectorypathis:+SDPATH);)/在 SD 卡上创建文件publicFilecreateSDFile(StringfileName)throwsIOExceptionFilefile=newFile(SDPATH+fileName);file.createNewF

2、ile();returnfile;)/在 SD 卡上创建目录publicFilecreateSDDir(StringdirName)Filedir=newFile(SDPATH+dirName);System.out.println(storgedevicesstate:+Environment.getExternalStorageState();if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)System.out.println(thisdirectoryrealpathis:+dir.get

3、AbsolutePath();System.out.println(theresultofmakingdirectory:+dir.mkdir();)returndir;)判断 SD 卡的文件夹是否存在publicbooleanisFileExist(StringfileName)Filefile=newFile(SDPATH+fileName);returnfile.exists();)将一个 inputStream 里面的数据写入到 SD 卡中publicFilewrite2SDFromInput(Stringpath,StringfileName,InputStreaminputStre

4、am)Filefile=null;OutputStreamoutput=null;tryFiletempf=createSDDir(path);System.out.println(directoryinthesdcard:+tempf.exists();file=createSDFile(path+fileName);output=newFileOutputStream(file);bytebuffer=newbyte4*1024;intlength=0;while(length=inputStream.read(buffer)!=-1)output.write(buffer,0,lengt

5、h);System.out.println(length);)output.flush();catch(FileNotFoundExceptione)e.printStackTrace();catch(IOExceptione)e.printStackTrace();finallytryoutput.close();catch(IOExceptione)e.printStackTrace();returnfile;HttpDownloader.java:;importjava.io.BufferedReader;importjava.io.File;importjava.io.IOExcept

6、ion;importjava.io.InputStream;importjava.io.InputStreamReader;.HttpURLConnection;.MalformedURLException;.URL;publicclassHttpDownloaderprivateURLurl=null;/* 下载步骤:* 1.创建一个 URL 对象* 2.通过 URL 对象,创建一个 HttpURLConnection 对象* 3.得至 UInputStream* 4.从 InputStream 当中读取数据* /publicStringdownload(StringurlStr)Strin

7、gBuffersb=newStringBuffer();Stringline=null;BufferedReaderbuffer=null;try(url=newURL(urlStr);HttpURLConnectionurlConn=(HttpURLConnection)url.openConnection();buffer=newBufferedReader(newInputStreamReader(urlConn.getInputStream();while(line=buffer.readLine()!=null)sb.append(line);catch(Exceptione)e.p

8、rintStackTrace();finallytrybuffer.close();catch(IOExceptione)e.printStackTrace();returnsb.toString();publicintdownFile(StringurlStr,Stringpath,StringfileName)InputStreaminputStream=null;tryFileUtilsfileUtils=newFileUtils();if(fileUtils.isFileExist(path+fileName)return1;elseinputStream=getInputStream

9、FromURL(urlStr);FileresultFile=fileUtils.write2SDFromInput(path,fileName,inputStream);if(resultFile=null)return-1;catch(Exceptione)e.printStackTrace();return-1;finallytryinputStream.close();catch(IOExceptione)e.printStackTrace();return0;publicInputStreamgetInputStreamFromURL(StringurlStr)HttpURLConn

10、ectionurlConn=null;InputStreaminputStream=null;tryurl=newURL(urlStr);urlConn=(HttpURLConnection)url.openConnection();inputStream=urlConn.getInputStream();catch(MalformedURLExceptione)e.printStackTrace();catch(IOExceptione)e.printStackTrace();returninputStream;HttpUploader.java:;importjava.io.Buffere

11、dReader;importjava.io.InputStreamReader;importjava.io.OutputStream;.InetAddress;.Socket;.URL;importjava.util.Map;publicclassHttpUploaderpublicstaticbooleanpost(Stringpath,Mapparams,FormFile 口files)throwsExceptionfinalStringBOUNDARY=7da2137580612”;finalStringendline=BOUNDARY+”-rn;intfileDataLength=0;

12、for(FormFileuploadFile:files)StringBuilderfileExplain=newStringBuilder();fileExplain.append(-);fileExplain.append(BOUNDARY);fileExplain.append(rn);fileExplain.append(Content-Disposition:form-data;name=+uploadFile.getParameterName()+;filename=+uploadFile.getFilename()+rn);fileExplain.append(Content-T

13、ype:+uploadFile.getContentType()+rnrn);fileExplain.append(rn);fileDataLength+=fileExplain.length();if(uploadFile.getInStream()!=null)fileDataLength+=uploadFile.getFile().length();elsefileDataLength+=uploadFile.getData().length;/*StringBuildertextEntity=newStringBuilder();for(Map.Entryentry:params.en

14、trySet()textEntity.append(-);textEntity.append(BOUNDARY);textEntity.append(rn);textEntity.append(Content-Disposition:form-data;name=+entry.getKey()+rnrn);textEntity.append(entry.getValue();textEntity.append(rn);intdataLength=textEntity.toString().getBytes().length+fileDataLength+endline.getBytes().l

15、ength;*/URLurl=newURL(path);intport=url.getPort()=-1?80:url.getPort();Socketsocket=newSocket(InetAddress.getByName(url.getHost(),port);OutputstreamoutStream=socket.getOutputStream();Stringrequestmethod=POST+url.getPath()+HTTP/1.1rn;outStream.write(requestmethod.getBytes();Stringaccept=Accept:image/g

16、if,image/jpeg,image/pjpeg,application/x-shockwave-flash,application/xaml+xml,application/vnd.ms-xpdocument,application/x-ms-xbap,application/x-ms-application,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*rn;outStream.write(accept.getBytes();Stringlanguage=Accept-Langua

17、ge:zh-CNrn;outStream.write(language.getBytes();Stringcontenttype=Content-Type:multipart/form-data;boundary=+BOUNDARY+rn;outStream.write(contenttype.getBytes();Stringcontentlength=Content-Length:+fileDataLength+rn;/Stringcontentlength=Content-Length:+dataLength+rn;outStream.write(contentlength.getByt

18、es();Stringalive=Connection:Keep-Alivern;outStream.write(alive.getBytes();Stringhost=Host:+url.getHost()+:+port+rn;outStream.write(host.getBytes();写完 HTTP 请求头后根据 HTTP 协议再写一个回车换行outStream.write(rn.getBytes();把所有文本类型的实体数据发送出来/outStream.write(textEntity.toString().getBytes();把所有文件类型的实体数据发送出来for(FormFil

19、euploadFile:files)StringBuilderfileEntity=newStringBuilder();fileEntity.append(-);fileEntity.append(BOUNDARY);fileEntity.append(rn);fileEntity.append(Content-Disposition:form-data;name=+uploadFile.getParameterName()+;filename=+uploadFile.getFilename()+rn);fileEntity.append(Content-Type:+uploadFile.g

20、etContentType()+rnrn);outStream.write(fileEntity.toString().getBytes();if(uploadFile.getInStream()!=null)bytebuffer=newbyte1024;intlen=0;while(len=uploadFile.getInStream().read(buffer,0,1024)!=-1)outStream.write(buffer,0,len);uploadFile.getInStream().close();elseoutStream.write(uploadFile.getData(),

21、0,uploadFile.getData().length);outStream.write(rn.getBytes();outStream.write(rn.getBytes();下面发送数据结束标志,表示数据已经结束outStream.write(endline.getBytes();/*BufferedReaderreader=newBufferedReader(newInputStreamReader(socket.getInputStream();if(reader.readLine().indexOf(200)=-1)读取 web 服务器返回的数据,判断请求码是否为 200,如果不

22、是 200,代表请求失败returnfalse;*/outStream.flush();outStream.close();/reader.close();socket.close();returntrue;)/*提交数据到服务器*parampath 上传路径(注:避免使用 localhost 或 这样的路径测试,因为它会指向手机模拟器,你可以使用 http:/ 或 0:8080 这样的路径测试)*paramparams 请求参数 key 为参数名,value 为参数值*paramfile 上传文件*/publicstaticboolean

23、post(Stringpath,MapString,Stringparams,FormFilefile)throwsExceptionreturnpost(path,params,newFormFilefile);)HttpclientActivity.java:;importjava.io.File;importjava.util.HashMap;importjava.util.Map;importandroid.app.Activity;importandroid.os.Bundle;importandroid.os.Environment;importandroid.os.Handler

24、;importandroid.util.Log;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.EditText;publicclassHttpclientActivityextendsActivityprivateEditTextdownloadText;privateButtondownloadButton;privateEditTextuploadfileText;privateButtonuploadButto

25、n;privateFilefile;privateHandlerhandler;privatestaticfinalStringTAG=MainActivity;/*Calledwhentheactivityisfirstcreated.*/OverridepublicvoidonCreate(BundlesavedInstanceState)super.onCreate(savedlnstanceState);setContentView(R.layout.main);downloadText=(EditText)findViewById(R.id.downloadfile);downloa

26、dButton=(Button)findViewById(R.id.download);downloadButton.setOnClickListener(newDownloadListener();uploadfileText=(EditText)findViewById(R.id.uploadfile);uploadButton=(Button)findViewById(R.id.upload);uploadButton.setOnClickListener(newUploadfileListener();classDownloadListenerimplementsOnClickListenerpublicvoidonClick(Viewv)Stringdownloadmsg=downloadText.getText().toString();

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论