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

下载本文档

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

文档简介

android之网络文件上传下载源码效果图:Main.xml: AndroidManifest.xml: 加上 FromFile.javapackage ;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;public class FormFile private bytedata;private InputStream inStream;private File file;private String filename;private String parameterName;private String contentType = application/octet-stream;public FormFile(String filename, byte data, String parameterName, String contentType) this.data = data;this.filename = filename;this.parameterName = parameterName;if(contentType!=null)this.contentType = contentType;public FormFile(String filename,File file,String parameterName,String contentType)this.filename = filename;this.parameterName = parameterName;this.file = file;trythis.inStream = new FileInputStream(file);catch(FileNotFoundException e)e.printStackTrace();if(contentType != null)this.contentType = contentType;public File getFile()return file;public InputStream getInStream()return inStream;public byte getData()return data;public String getFilename()return filename;public void setFilename(String filename)this.filename = filename;public String getParameterName()return parameterName;public void setParameterName(String parameterName)this.parameterName = parameterName;public String getContentType()return contentType;public void setContentType(String contentType)this.contentType = contentType;FileUtils.java:package ;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import android.os.Environment;public class FileUtils private String SDPATH;public String getSDPATH()return SDPATH;public void setSDPATH(String sDPATH)SDPATH = sDPATH;/获取SD卡目录public FileUtils()SDPATH = Environment.getExternalStorageDirectory() + /;System.out.println(sd cards directory path is : + SDPATH);/在SD卡上创建文件public File createSDFile(String fileName)throws IOExceptionFile file = new File(SDPATH + fileName);file.createNewFile();return file;/在SD卡上创建目录public File createSDDir(String dirName)File dir = new File(SDPATH + dirName);System.out.println(storge devices state : +Environment.getExternalStorageState();if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)System.out.println(this directory real path is:+dir.getAbsolutePath();System.out.println(the result of making directory:+dir.mkdir();return dir;/判断SD卡的文件夹是否存在public boolean isFileExist(String fileName)File file = new File(SDPATH + fileName);return file.exists();/将一个inputStream里面的数据写入到SD卡中public File write2SDFromInput(String path,String fileName,InputStream inputStream)File file = null;OutputStream output = null;tryFile tempf = createSDDir(path);System.out.println(directory in the sd card: + tempf.exists();file = createSDFile(path + fileName);output = new FileOutputStream(file);byte buffer = new byte4*1024;int length = 0;while(length = inputStream.read(buffer) != -1)output.write(buffer, 0, length);System.out.println(length);output.flush();catch(FileNotFoundException e)e.printStackTrace();catch(IOException e)e.printStackTrace();finallytryoutput.close();catch(IOException e)e.printStackTrace();return file;HttpDownloader.java:package ;import java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import .HttpURLConnection;import .MalformedURLException;import .URL;public class HttpDownloader private URL url = null;/* * 下载步骤: * 1.创建一个URL对象 * 2.通过URL对象,创建一个HttpURLConnection对象 * 3.得到InputStream * 4.从InputStream当中读取数据 */public String download(String urlStr)StringBuffer sb = new StringBuffer();String line = null;BufferedReader buffer = null;tryurl = new URL(urlStr);HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream();while(line = buffer.readLine() != null)sb.append(line);catch(Exception e)e.printStackTrace();finallytrybuffer.close();catch(IOException e)e.printStackTrace();return sb.toString();public int downFile(String urlStr, String path, String fileName)InputStream inputStream = null;tryFileUtils fileUtils = new FileUtils();if(fileUtils.isFileExist(path + fileName)return 1;elseinputStream = getInputStreamFromURL(urlStr);File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);if(resultFile = null)return -1;catch(Exception e)e.printStackTrace();return -1;finallytryinputStream.close();catch(IOException e)e.printStackTrace();return 0;public InputStream getInputStreamFromURL(String urlStr)HttpURLConnection urlConn = null;InputStream inputStream = null;tryurl = new URL(urlStr);urlConn = (HttpURLConnection)url.openConnection();inputStream = urlConn.getInputStream();catch(MalformedURLException e)e.printStackTrace();catch(IOException e)e.printStackTrace();return inputStream;HttpUploader.java:package ;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStream;import .InetAddress;import .Socket;import .URL;import java.util.Map;public class HttpUploader public static boolean post(String path, Map params, FormFile files)throws Exceptionfinal String BOUNDARY = -7da2137580612;final String endline = BOUNDARY + -rn;int fileDataLength = 0;for(FormFile uploadFile : files)StringBuilder fileExplain = new StringBuilder();fileExplain.append(-);fileExplain.append(BOUNDARY);fileExplain.append(rn);fileExplain.append(Content-Disposition:form-data;name=+ uploadFile.getParameterName()+;filename=+ uploadFile.getFilename() + rn);fileExplain.append(Content-Type: + uploadFile.getContentType()+rnrn);fileExplain.append(rn);fileDataLength += fileExplain.length();if(uploadFile.getInStream()!=null)fileDataLength += uploadFile.getFile().length();elsefileDataLength += uploadFile.getData().length;/*StringBuilder textEntity = new StringBuilder();for(Map.Entry entry : params.entrySet()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);int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length; */URL url = new URL(path);int port = url.getPort() = -1 ? 80 : url.getPort();Socket socket = new Socket(InetAddress.getByName(url.getHost(), port); OutputStream outStream = socket.getOutputStream();String requestmethod = POST + url.getPath()+ HTTP/1.1rn; outStream.write(requestmethod.getBytes();String accept = Accept:image/gif,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();String language = Accept-Language: zh-CNrn;outStream.write(language.getBytes();String contenttype = Content-Type: multipart/form-data; boundary=+ BOUNDARY+ rn;outStream.write(contenttype.getBytes();String contentlength = Content-Length: + fileDataLength + rn;/String contentlength = Content-Length: + dataLength + rn;outStream.write(contentlength.getBytes();String alive = Connection: Keep-Alivern;outStream.write(alive.getBytes();String host = Host: + url.getHost() +:+ port +rn;outStream.write(host.getBytes();/写完HTTP请求头后根据HTTP协议再写一个回车换行 outStream.write(rn.getBytes(); /把所有文本类型的实体数据发送出来 / outStream.write(textEntity.toString().getBytes(); /把所有文件类型的实体数据发送出来 for(FormFile uploadFile : files) StringBuilder fileEntity = new StringBuilder(); 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.getContentType()+rnrn); outStream.write(fileEntity.toString().getBytes(); if(uploadFile.getInStream()!=null) byte buffer = new byte1024; int len = 0; while(len = uploadFile.getInStream().read(buffer, 0, 1024)!=-1) outStream.write(buffer, 0, len); uploadFile.getInStream().close(); else outStream.write(uploadFile.getData(), 0, uploadFile.getData().length); outStream.write(rn.getBytes(); outStream.write(rn.getBytes(); /下面发送数据结束标志,表示数据已经结束 outStream.write(endline.getBytes(); /* BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(); if(reader.readLine().indexOf(200)=-1) /读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败 return false; */ outStream.flush(); outStream.close(); / reader.close(); socket.close(); return true; /* * 提交数据到服务器 * * param path 上传路径(注:避免使用localhost或这样的路径测试,因为它会指向手机模拟器,你可以使用或0:8080这样的路径测试) * * param params 请求参数 key为参数名,value为参数值 * * param file 上传文件 */ public static boolean post(String path, Map params, FormFile file) throws Exceptionreturn post(path, params, new FormFilefile);HttpclientActivity.java:package ;import java.io.File;import java.util.HashMap;import java.util.Map;import android.app.Activity;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;public class HttpclientActivity extends Activity private EditText downloadText;private Button downloadButton;private EditText uploadfileText;private Button uploadButton;private File file;private Handler handler;private static final String TAG=MainActivity; /* Called when the activity is first created. */ Override public void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState); setContentView(R.layout.main); downloadText = (EditText)findViewById(R.id.downloadfile); downloadButton = (Button)findViewById(R.id.download); downloadButton.setOnClickListener(new DownloadListener(); uploadfileText = (EditText)findViewById(R.id.uploadfile); uploadButton = (Button)findViewById(R.id.upload); uploadButton.setOnClickLi

温馨提示

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

最新文档

评论

0/150

提交评论