package com.zhougan.upload.util; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.UUID; /** * Created by 1 on 2016/3/19. */ public class UploadUtil { private static final String PREFIX = "--"; //前缀 private static final String BOUNDARY = UUID.randomUUID().toString();//随机生成数据分割符 private static final String End_LINE = "\r\n";//换行 private URL url=null; private int connTimeOut = 5 * 1000;//连接超时 private int readTimeOut = 5 * 1000;//读取超时 private List<Content> lists;//存放要发送的内容 private HttpURLConnection conn; private CallbackResponse callbackResponse;//处理响应的回调接口 public UploadUtil() { } //向服务器发送数据 public void sendData(){ new Thread(new Runnable() { @Override public void run() { setHttpHeader();//设置请求头 DataOutputStream dos = null; FileInputStream fis=null;//读取要发送的文件 try { dos=new DataOutputStream(conn.getOutputStream());//用数据流包装输出流 for(Content content : lists){//遍历要发送的数据 //发送内容信息 dos.write(content.getContentHeader().getBytes(content.charset)); //发送文件 if(content.isFile){ File file = content.getFile(); fis=new FileInputStream(file); byte[] buf=new byte[1024*10];//10k缓存 int len=0; while((len=fis.read(buf))!=-1){ dos.write(buf,0,len); } dos.flush(); dos.write(End_LINE.getBytes());//发送完毕换行 if(fis!=null){ fis.close();fis=null; } }else{//发送字符串 dos.write(content.getStringData()); } } //发送结束标志 dos.write((PREFIX+BOUNDARY+PREFIX+End_LINE).getBytes()); dos.flush(); if(dos!=null){ dos.close();dos=null; } //处理响应 if(conn.getResponseCode()==200){ // System.out.println("200"); if(callbackResponse!=null){ callbackResponse.response(conn); } } } catch (IOException e) { e.printStackTrace(); }finally{ try {//关闭所有流和连接 if(fis!=null){ fis.close(); } if(dos!=null){ dos.close(); } if(conn!=null){ conn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } } }).start(); } //设置请求头 private void setHttpHeader(){ try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST");//post方式发送 conn.setConnectTimeout(connTimeOut);//设置连接超时 conn.setReadTimeout(readTimeOut);//设置读取超时 conn.setUseCaches(false);//禁用缓存 conn.setDoOutput(true);//允许输出 conn.setDoInput(true);//允许输入 //以表单的形式发送 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); conn.setRequestProperty("Connection", "Keep-Alive");//保持长连接 } catch (IOException e) { e.printStackTrace(); } } //添加要发送的数据 public void setData(List<Content> lists){ this.lists=lists; } public void setUrl(URL url) { this.url = url; } public int getConnTimeOut() { return connTimeOut; } public void setConnTimeOut(int connTimeOut) { this.connTimeOut = connTimeOut; } public int getReadTimeOut() { return readTimeOut; } public void setReadTimeOut(int readTimeOut) { this.readTimeOut = readTimeOut; } public void setCallbackResponse(CallbackResponse callbackResponse) { this.callbackResponse = callbackResponse; } //定义发送的数据 一个Content表示一条数据 public static class Content{ private String type="text/plain";//默认文本类型 private String charset="utf-8";//默认utf-8编码 private long contentLength=0;//文件内容长度 private String name="name";//服务器获得数据的key private String value="value";//字符串数据内容 private File file;//文件 private String filename="filename";//文件名字 private boolean isFile=false;//本条数据是否是文件 //无参构造器,使用默认的类型和编码 public Content(){ } //编码,类型 public Content(String charset, String type) { if(charset!=null) this.charset = charset; if(type!=null) this.type = type; } //设置要发送的字符串数据 public void setData(String name,String value){ isFile=false; if(name!=null) this.name=name; if(value!=null) this.value=value; } //设置要发送的文件 public void setData(String name,File file){ isFile=true; if(name!=null) this.name=name; if(file!=null){ this.file=file; this.filename=file.getName(); contentLength=file.length(); } } //获得字符串数据 private byte[] getStringData(){ StringBuffer sb=new StringBuffer(); sb.append(value); sb.append(End_LINE);//发送完了换行 try { return sb.toString().getBytes(charset); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } //构建内容头 private String getContentHeader(){ StringBuffer sb=new StringBuffer(); sb.append(PREFIX + BOUNDARY + End_LINE);//分割数据 //设置本条数据的信息 if(isFile){//文件 sb.append("Content-Disposition: form-data; name=\""+name+"\""+"; filename=\""+filename+"\""+End_LINE); if(contentLength>0){ sb.append("Content-Length: "+String.valueOf(contentLength)+End_LINE); } }else{//非文件 sb.append("Content-Disposition: form-data; name=\""+name+"\""+End_LINE); } //类型 和编码 sb.append("Content-Type: "+type +"; charset="+charset + End_LINE); sb.append(End_LINE);//数据信息和数据内容之间空一行 return sb.toString(); } //获取文件 private File getFile(){ return file; } } //处理响应的回调接口(可以不用,如果不需要处理响应) public interface CallbackResponse{ void response(HttpURLConnection conn); } }
应项目需要,弄了个多文件上传,分享给大家,求指正,共进步
最新推荐文章于 2019-06-21 09:50:38 发布