android之網(wǎng)絡(luò)文件上傳下載源碼_第1頁(yè)
android之網(wǎng)絡(luò)文件上傳下載源碼_第2頁(yè)
android之網(wǎng)絡(luò)文件上傳下載源碼_第3頁(yè)
android之網(wǎng)絡(luò)文件上傳下載源碼_第4頁(yè)
android之網(wǎng)絡(luò)文件上傳下載源碼_第5頁(yè)
免費(fèi)預(yù)覽已結(jié)束,剩余7頁(yè)可下載查看

下載本文檔

版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、android 之網(wǎng)絡(luò)文件上傳下載源碼01:54AMLinearLayoutxmlns:android=http: SD 卡目錄publicFileUtils()SDPATH=Environment.getExternalStorageDirectory()+/;System.out.println(sdcardsdirectorypathis:+SDPATH);)/在 SD 卡上創(chuàng)建文件publicFilecreateSDFile(StringfileName)throwsIOExceptionFilefile=newFile(SDPATH+fileName);file.createNewF

2、ile();returnfile;)/在 SD 卡上創(chuàng)建目錄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();)將一個(gè) inputStream 里面的數(shù)據(jù)寫(xiě)入到 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.創(chuàng)建一個(gè) URL 對(duì)象* 2.通過(guò) URL 對(duì)象,創(chuàng)建一個(gè) HttpURLConnection 對(duì)象* 3.得至 UInputStream* 4.從 InputStream 當(dāng)中讀取數(shù)據(jù)* /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();寫(xiě)完 HTTP 請(qǐng)求頭后根據(jù) HTTP 協(xié)議再寫(xiě)一個(gè)回車(chē)換行outStream.write(rn.getBytes();把所有文本類(lèi)型的實(shí)體數(shù)據(jù)發(fā)送出來(lái)/outStream.write(textEntity.toString().getBytes();把所有文件類(lèi)型的實(shí)體數(shù)據(jù)發(fā)送出來(lái)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();下面發(fā)送數(shù)據(jù)結(jié)束標(biāo)志,表示數(shù)據(jù)已經(jīng)結(jié)束outStream.write(endline.getBytes();/*BufferedReaderreader=newBufferedReader(newInputStreamReader(socket.getInputStream();if(reader.readLine().indexOf(200)=-1)讀取 web 服務(wù)器返回的數(shù)據(jù),判斷請(qǐng)求碼是否為 200,如果不

22、是 200,代表請(qǐng)求失敗returnfalse;*/outStream.flush();outStream.close();/reader.close();socket.close();returntrue;)/*提交數(shù)據(jù)到服務(wù)器*parampath 上傳路徑(注:避免使用 localhost 或 這樣的路徑測(cè)試,因?yàn)樗鼤?huì)指向手機(jī)模擬器,你可以使用 http:/ 或 0:8080 這樣的路徑測(cè)試)*paramparams 請(qǐng)求參數(shù) key 為參數(shù)名,value 為參數(shù)值*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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論