android中使用HTTP协议和TCP协议实现上传文件

android服务器端上传方法:


    package cn.test.web.servlet;  
      
    import java.io.File;  
    import java.io.IOException;  
    import java.util.List;  
      
    import javax.servlet.ServletException;  
    import javax.servlet.http.HttpServlet;  
    import javax.servlet.http.HttpServletRequest;  
    import javax.servlet.http.HttpServletResponse;  
      
    import org.apache.commons.fileupload.FileItem;  
    import org.apache.commons.fileupload.FileItemFactory;  
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
    import org.apache.commons.fileupload.servlet.ServletFileUpload;  
      
    public class LoginServlet extends HttpServlet {  
      
        private static final long serialVersionUID = 1L;  
      
        @Override  
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
            doPost(request, response);  
        }  
      
        @Override  
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
            if (isMultipart)  
                try {  
                    FileItemFactory factory = new DiskFileItemFactory();  
                    ServletFileUpload upload = new ServletFileUpload(factory);  
                    List<FileItem> items = upload.parseRequest(request);  
                    File dir = new File(request.getSession().getServletContext().getRealPath("/WEB-INF/upload"));  
                    //创建目录  
                    dir.mkdir();  
                    for (FileItem item : items)  
                        if (item.isFormField())  
                            System.out.println(item.getFieldName() + ": " + item.getString());  
                        else{  
                            item.write(new File(dir,item.getName().substring(item.getName().lastIndexOf("\\")+1)));  
                        }  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            else {  
                System.out.println(request.getMethod());  
                System.out.println(request.getParameter("username"));  
                System.out.println(request.getParameter("password"));  
            }  
        }  
    }  
android客户器端上传方法:
首先,要有一个javaBean类FormFile封装文件的信息:
public class FormFile {
/* 上传文件的数据 */
private byte[] data;
/* 文件名称 */
private String filname;
/* 表单字段名称*/
private String formname;
/* 内容类型 */
private String contentType = "application/octet-stream"; //需要查阅相关的资料

public FormFile(String filname, byte[] data, String formname, String contentType) {
  this.data = data;
  this.filname = filname;
  this.formname = formname;
  if(contentType!=null) this.contentType = contentType;
}

public byte[] getData() {
  return data;
}

public void setData(byte[] data) {
  this.data = data;
}

public String getFilname() {
  return filname;
}

public void setFilname(String filname) {
  this.filname = filname;
}

public String getFormname() {
  return formname;
}

public void setFormname(String formname) {
  this.formname = formname;
}

public String getContentType() {
  return contentType;
}

public void setContentType(String contentType) {
  this.contentType = contentType;
}

}

实现文件上传的代码如下:
/**
* 直接通过HTTP协议提交数据到服务器,实现表单提交功能
* @param actionUrl 上传路径
* @param params 请求参数 key为参数名,value为参数值
* @param file 上传文件
*/
public static String post(String actionUrl, Map<String, String> params, FormFile[] files) {  
    try {            
        String BOUNDARY = “———7d4a6d158c9″; //数据分隔线  
        String MULTIPART_FORM_DATA = “multipart/form-data”;  
         
        URL url = new URL(actionUrl);  
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
        conn.setDoInput(true);//允许输入  
        conn.setDoOutput(true);//允许输出  
        conn.setUseCaches(false);//不使用Cache  
        conn.setRequestMethod(”POST”);            
        conn.setRequestProperty(”Connection”, “Keep-Alive”);  
        conn.setRequestProperty(”Charset”, “UTF-8″);  
        conn.setRequestProperty(”Content-Type”, MULTIPART_FORM_DATA + “; boundary=” + BOUNDARY);  

        StringBuilder sb = new StringBuilder();  
         
        //上传的表单参数部分,格式请参考文章  
        for (Map.Entry<String, String> entry : params.entrySet()) {//构建表单字段内容  
            sb.append(”–”);  
            sb.append(BOUNDARY);  
            sb.append(”\r\n”);  
            sb.append(”Content-Disposition: form-data; name=\”"+ entry.getKey() + “\”\r\n\r\n”);  
            sb.append(entry.getValue());  
            sb.append(”\r\n”);  
        }  
        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());  
        outStream.write(sb.toString().getBytes());//发送表单字段数据  
         
        //上传的文件部分,格式请参考文章  
        for(FormFile file : files){  
            StringBuilder split = new StringBuilder();  
            split.append(”–”);  
            split.append(BOUNDARY);  
            split.append(”\r\n”);  
            split.append(”Content-Disposition: form-data;name=\”"+ file.getFormname()+”\”;filename=\”"+ file.getFilname() + “\”\r\n”);  
            split.append(”Content-Type: “+ file.getContentType()+”\r\n\r\n”);  
            outStream.write(split.toString().getBytes());  
            outStream.write(file.getData(), 0, file.getData().length);  
            outStream.write(”\r\n”.getBytes());  
        }  
        byte[] end_data = (”–” + BOUNDARY + “–\r\n”).getBytes();//数据结束标志           
        outStream.write(end_data);  
        outStream.flush();  
        int cah = conn.getResponseCode();  
        if (cah != 200) throw new RuntimeException(”请求url失败”);  
        InputStream is = conn.getInputStream();  
        int ch;  
        StringBuilder b = new StringBuilder();  
        while( (ch = is.read()) != -1 ){  
            b.append((char)ch);  
        }  
        outStream.close();  
        conn.disconnect();  
        return b.toString();  
    } catch (Exception e) {  
        throw new RuntimeException(e);  
    }  
}  








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值