分享一个volley支持 multipart上传文件

直接上代码,首先自定义的request:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class MultipartRequest extends Request<JSONObject> {  
  2.       
  3.     private VolleyErrorListener errorListener = null;  
  4.     private VolleyResponseListener listener = null;  
  5.     private MultipartRequestParams params = null;  
  6.     private HttpEntity httpEntity = null;  
  7.       
  8.     public MultipartRequest(String url, VolleyJsonResponseHandler handler, MultipartRequestParams params) {  
  9.         this(Method.POST,params, url, handler, null);  
  10.     }  
  11.       
  12.     public MultipartRequest(int method,MultipartRequestParams params, String url, VolleyJsonResponseHandler handler,   
  13.             Context context) {  
  14.         super(method, RequestUrl.BASE_URL + url, null);  
  15.         // TODO Auto-generated constructor stub  
  16.         this.params = params;  
  17.         this.errorListener = new VolleyErrorListener(context, handler, falsethis);   
  18.         this.listener = new VolleyResponseListener(context, handler);  
  19.     }  
  20.   
  21.     @Override  
  22.     public byte[] getBody() throws AuthFailureError {  
  23.         // TODO Auto-generated method stub  
  24.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  25.         if(params != null) {  
  26.             httpEntity = params.getEntity();   
  27.             try {  
  28.                 httpEntity.writeTo(baos);  
  29.             } catch (IOException e) {  
  30.                 // TODO Auto-generated catch block  
  31.                 e.printStackTrace();  
  32.                 Logger.d("IOException writing to ByteArrayOutputStream");  
  33.             }  
  34.             String str = new String(baos.toByteArray());  
  35.             Logger.d("bodyString is :" + str);  
  36.         }  
  37.         return baos.toByteArray();  
  38.     }  
  39.       
  40.     @Override  
  41.     protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {  
  42.         // TODO Auto-generated method stub  
  43.         try {  
  44.             String jsonString = new String(response.data,  
  45.                     HttpHeaderParser.parseCharset(response.headers));  
  46.             return Response.success(new JSONObject(jsonString),  
  47.                     HttpHeaderParser.parseCacheHeaders(response));  
  48.         } catch (UnsupportedEncodingException e) {  
  49.             errorListener.setFlag(false);  
  50.             return Response.error(new ParseError(response));  
  51.         } catch (JSONException je) {  
  52.             errorListener.setFlag(false);  
  53.             return Response.error(new ParseError(response));  
  54.         }  
  55.     }  
  56.   
  57.     @Override  
  58.     public Map<String, String> getHeaders() throws AuthFailureError {  
  59.         // TODO Auto-generated method stub  
  60.         Map<String, String> headers = super.getHeaders();  
  61.         if (null == headers || headers.equals(Collections.emptyMap())) {  
  62.             headers = new HashMap<String, String>();  
  63.         }  
  64.         MainApplication.getInstance().addSessionCookie(headers);  
  65.         return headers;  
  66.     }  
  67.       
  68.     @Override  
  69.     public String getBodyContentType() {  
  70.         // TODO Auto-generated method stub  
  71.         String str = httpEntity.getContentType().getValue();  
  72.         return httpEntity.getContentType().getValue();  
  73.     }  
  74.       
  75.     @Override  
  76.     protected void deliverResponse(JSONObject response) {  
  77.         // TODO Auto-generated method stub  
  78.         listener.onResponse(response);   
  79.     }  
  80.       
  81.     @Override  
  82.     public void deliverError(VolleyError error) {  
  83.         // TODO Auto-generated method stub  
  84.         if(errorListener != null) {  
  85.             errorListener.onErrorResponse(error);  
  86.         }  
  87.     }  
MultipartParams文件:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public class MultipartRequestParams {  
  2.     protected ConcurrentHashMap<String, String> urlParams;  
  3.     protected ConcurrentHashMap<String, FileWrapper> fileParams;  
  4.       
  5.     public MultipartRequestParams() {  
  6.         init();  
  7.     }  
  8.       
  9.     public MultipartRequestParams(String key, String value) {  
  10.         init();  
  11.         put(key, value);  
  12.     }  
  13.       
  14.     private void init() {  
  15.         urlParams = new ConcurrentHashMap<String, String>();  
  16.         fileParams = new ConcurrentHashMap<String, FileWrapper>();  
  17.     }  
  18.       
  19.     /** 
  20.      * 添加value到request中 
  21.      * @param key 
  22.      * @param value 
  23.      */  
  24.     public void put(String key, String value) {  
  25.         if(key != null && value != null) {  
  26.             urlParams.put(key, value);  
  27.         }  
  28.     }  
  29.     /** 
  30.      * 添加文件到request中 
  31.      * @param key 
  32.      * @param file 
  33.      */  
  34.     public void put(String key, File file) {  
  35.         try {  
  36.             put(key, new FileInputStream(file), file.getName());  
  37.         } catch (FileNotFoundException e) {  
  38.             // TODO Auto-generated catch block  
  39.             e.printStackTrace();  
  40.             Logger.d("MultipartRequestParams file not found!!!");  
  41.         }  
  42.     }  
  43.       
  44.     /** 
  45.      * 添加stream到request中 
  46.      * @param key 
  47.      * @param stream 
  48.      * @param fileName 
  49.      */  
  50.     public void put(String key, InputStream stream, String fileName) {  
  51.         put(key, stream, fileName, null);  
  52.     }  
  53.       
  54.     /** 
  55.      * 添加stream到request中 
  56.      * @param key 
  57.      * @param stream 
  58.      * @param fileName 
  59.      * @param contentType 
  60.      */  
  61.     public void put(String key, InputStream stream, String fileName, String contentType) {  
  62.         if(key != null && stream != null) {  
  63.             fileParams.put(key, new FileWrapper(stream, fileName, contentType));  
  64.         }  
  65.     }  
  66.       
  67.     public HttpEntity getEntity() {  
  68.         HttpEntity entity = null;  
  69.         if(!fileParams.isEmpty()) {  
  70.             MultipartEntity multipartEntity = new MultipartEntity();  
  71.   
  72.             // Add string params  
  73.             for(ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {  
  74.                 multipartEntity.addPart(entry.getKey(), entry.getValue());  
  75.             }  
  76.   
  77.             // Add file params  
  78.             int currentIndex = 0;  
  79.             int lastIndex = fileParams.entrySet().size() - 1;  
  80.             for(ConcurrentHashMap.Entry<String, FileWrapper> entry : fileParams.entrySet()) {  
  81.                 FileWrapper file = entry.getValue();  
  82.                 if(file.inputStream != null) {  
  83.                     boolean isLast = currentIndex == lastIndex;  
  84.                     if(file.contentType != null) {  
  85.                         multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, file.contentType, isLast);  
  86.                     } else {  
  87.                         multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, isLast);  
  88.                     }  
  89.                 }  
  90.                 currentIndex++;  
  91.             }  
  92.   
  93.             entity = multipartEntity;  
  94.         }   
  95.         return entity;  
  96.     }  
  97.       
  98.     private static class FileWrapper {  
  99.         public InputStream inputStream;  
  100.         public String fileName;  
  101.         public String contentType;  
  102.   
  103.         public FileWrapper(InputStream inputStream, String fileName,  
  104.                 String contentType) {  
  105.             this.inputStream = inputStream;  
  106.             this.fileName = fileName;  
  107.             this.contentType = contentType;  
  108.         }  
  109.   
  110.         public String getFileName() {  
  111.             if (fileName != null) {  
  112.                 return fileName;  
  113.             } else {  
  114.                 return "nofilename";  
  115.             }  
  116.         }  
  117.     }  
MultipartEntity文件:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. class MultipartEntity implements HttpEntity {  
  2.     private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();  
  3.   
  4.     private String boundary = null;  
  5.   
  6.     ByteArrayOutputStream out = new ByteArrayOutputStream();  
  7.     boolean isSetLast = false;  
  8.     boolean isSetFirst = false;  
  9.   
  10.     public MultipartEntity() {  
  11.         final StringBuffer buf = new StringBuffer();  
  12.         final Random rand = new Random();  
  13.         for (int i = 0; i < 30; i++) {  
  14.             buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);  
  15.         }  
  16.         this.boundary = buf.toString();  
  17.   
  18.     }  
  19.   
  20.     public void writeFirstBoundaryIfNeeds(){  
  21.         if(!isSetFirst){  
  22.             try {  
  23.                 out.write(("--" + boundary + "\r\n").getBytes());  
  24.             } catch (final IOException e) {  
  25.                 e.printStackTrace();  
  26.             }  
  27.         }  
  28.   
  29.         isSetFirst = true;  
  30.     }  
  31.   
  32.     public void writeLastBoundaryIfNeeds() {  
  33.         if(isSetLast){  
  34.             return;  
  35.         }  
  36.   
  37.         try {  
  38.             out.write(("\r\n--" + boundary + "--\r\n").getBytes());  
  39.         } catch (final IOException e) {  
  40.             e.printStackTrace();  
  41.         }  
  42.   
  43.         isSetLast = true;  
  44.     }  
  45.   
  46.     public void addPart(final String key, final String value) {  
  47.         writeFirstBoundaryIfNeeds();  
  48.         try {  
  49.             out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n\r\n").getBytes());  
  50.             out.write(value.getBytes());  
  51.             out.write(("\r\n--" + boundary + "\r\n").getBytes());  
  52.         } catch (final IOException e) {  
  53.             e.printStackTrace();  
  54.         }  
  55.     }  
  56.   
  57.     public void addPart(final String key, final String fileName, final InputStream fin, final boolean isLast){  
  58.         addPart(key, fileName, fin, "application/octet-stream", isLast);  
  59.     }  
  60.   
  61.     public void addPart(final String key, final String fileName, final InputStream fin, String type, final boolean isLast){  
  62.         writeFirstBoundaryIfNeeds();  
  63.         try {  
  64.             type = "Content-Type: "+type+"\r\n";  
  65.             out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());  
  66.             out.write(type.getBytes());  
  67.             out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());  
  68.   
  69.             final byte[] tmp = new byte[4096];  
  70.             int l = 0;  
  71.             while ((l = fin.read(tmp)) != -1) {  
  72.                 out.write(tmp, 0, l);  
  73.             }  
  74.             if(!isLast)  
  75.                 out.write(("\r\n--" + boundary + "\r\n").getBytes());  
  76.             else {  
  77.                 writeLastBoundaryIfNeeds();  
  78.             }  
  79.             out.flush();  
  80.         } catch (final IOException e) {  
  81.             e.printStackTrace();  
  82.         } finally {  
  83.             try {  
  84.                 fin.close();  
  85.             } catch (final IOException e) {  
  86.                 e.printStackTrace();  
  87.             }  
  88.         }  
  89.     }  
  90.   
  91.     public void addPart(final String key, final File value, final boolean isLast) {  
  92.         try {  
  93.             addPart(key, value.getName(), new FileInputStream(value), isLast);  
  94.         } catch (final FileNotFoundException e) {  
  95.             e.printStackTrace();  
  96.         }  
  97.     }  
  98.   
  99.     @Override  
  100.     public long getContentLength() {  
  101.         writeLastBoundaryIfNeeds();  
  102.         return out.toByteArray().length;  
  103.     }  
  104.   
  105.     @Override  
  106.     public Header getContentType() {  
  107.         return new BasicHeader("Content-Type""multipart/form-data; boundary=" + boundary);  
  108.     }  
  109.   
  110.     @Override  
  111.     public boolean isChunked() {  
  112.         return false;  
  113.     }  
  114.   
  115.     @Override  
  116.     public boolean isRepeatable() {  
  117.         return false;  
  118.     }  
  119.   
  120.     @Override  
  121.     public boolean isStreaming() {  
  122.         return false;  
  123.     }  
  124.   
  125.     @Override  
  126.     public void writeTo(final OutputStream outstream) throws IOException {  
  127.         outstream.write(out.toByteArray());  
  128.     }  
  129.   
  130.     @Override  
  131.     public Header getContentEncoding() {  
  132.         return null;  
  133.     }  
  134.   
  135.     @Override  
  136.     public void consumeContent() throws IOException,  
  137.     UnsupportedOperationException {  
  138.         if (isStreaming()) {  
  139.             throw new UnsupportedOperationException(  
  140.             "Streaming entity does not implement #consumeContent()");  
  141.         }  
  142.     }  
  143.   
  144.     @Override  
  145.     public InputStream getContent() throws IOException,  
  146.     UnsupportedOperationException {  
  147.         return new ByteArrayInputStream(out.toByteArray());  
  148.     }  

其实MultipartParams和MultipartEntity主要都是用开源的AsyncHttpClient里面的源文件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值