Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
      This code is taken from Rafael Sanches' blog.
      http://blog.rafaelsanches.com/2011/01/29/upload-using-multipart-post-using-httpclient-in-android/
  */
  
  package com.qiniu.android.http;
  
  
 import  org.apache.http.message.BasicHeader;
 import  org.apache.http.protocol.HTTP;
 
 import java.io.File;
 
 
 final class MultipartBuilder {
 
     private static final String STR_CR_LF = "\r\n";
     private static final byte[] CR_LF = {'\r''\n'};
     private static final byte[] TRANSFER_ENCODING_BINARY =
             ("Content-Transfer-Encoding: binary" + ).getBytes();
 
     private final static char[] MULTIPART_CHARS =
             "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
 
     private final String boundary;
     private final byte[] boundaryLine;
     private final byte[] boundaryEnd;
 
 
     private final ByteArrayOutputStream out = new ByteArrayOutputStream();
 
     public MultipartBuilder() {
         final StringBuilder buf = new StringBuilder();
         final Random rand = new Random();
         for (int i = 0; i < 30; i++) {
             buf.append([rand.nextInt(.)]);
         }
 
          = buf.toString();
          = ("--" +  + ).getBytes();
          = ("--" +  + "--" + ).getBytes();
 
     }

    
Appends a quoted-string to a StringBuilder.

RFC 2388 is rather vague about how one should escape special characters in form-data parameters, and as it turns out Firefox and Chrome actually do rather different things, and both say in their comments that they're not really sure what the right approach is. We go with Chrome's behavior (which also experimentally seems to match what IE does), but if you actually want to have a good chance of things working, please avoid double-quotes, newlines, percent signs, and the like in your field names.

 
     private static StringBuilder appendQuotedString(StringBuilder targetString key) {
         target.append('"');
         for (int i = 0, len = key.length(); i < leni++) {
             char ch = key.charAt(i);
             switch (ch) {
                 case '\n':
                     target.append("%0A");
                     break;
                 case '\r':
                     target.append("%0D");
                     break;
                 case '"':
                     target.append("%22");
                     break;
                 default:
                     target.append(ch);
                     break;
             }
         }
         target.append('"');
         return target;
     }
 
     public void addPart(String keyString valueString contentType) {
         try {
             .write();
             .write(createContentDisposition(key));
             .write(createContentType(contentType));
             .write();
             .write(value.getBytes());
             .write();
         } catch (final IOException e) {
             throw new AssertionError(e);
         }
     }
 
     public void addPartWithCharset(String keyString valueString charset) {
         if (charset == nullcharset = HTTP.UTF_8;
        addPart(keyvalue"text/plain; charset=" + charset);
    }
    public void addPart(String keyString value) {
        addPartWithCharset(keyvaluenull);
    }
    public void addPart(String keyFile filethrows IOException {
        addPart(keyfilenullfile.getName());
    }
    public void addPart(String keyFile fileString typeString customFileNamethrows IOException {
        FileInputStream fis = new FileInputStream(file);
        IOException e = null;
        try {
            addPart(keycustomFileNamefistype);
        } catch (IOException e1) {
            e = e1;
        }
        fis.close();
        if (e != null) {
            throw e;
        }
    }
    public void addPart(String keyString streamNameInputStream inputStreamString type)
            throws IOException {
        .write();
        // Headers
        .write(createContentDisposition(keystreamName));
        .write(createContentType(type));
        .write();
        // Stream (file)
        final byte[] tmp = new byte[1024 * 8];
        int l;
        while ((l = inputStream.read(tmp)) != -1) {
            .write(tmp, 0, l);
        }
        .write();
    }
    private String normalizeContentType(String type) {
        return type == null ? HTTP.DEFAULT_CONTENT_TYPE : type;
    }
    private byte[] createContentType(String type) {
        String result = HTTP.CONTENT_TYPE + ": " + normalizeContentType(type) + ;
        return result.getBytes();
    }
    private byte[] createContentDisposition(String key) {
        StringBuilder builder = new StringBuilder("Content-Disposition: form-data; name=");
        appendQuotedString(builderkey);
        builder.append();
        return StringUtils.utf8Bytes(builder.toString());
    }
    private byte[] createContentDisposition(String keyString fileName) {
        StringBuilder builder = new StringBuilder("Content-Disposition: form-data; name=");
        appendQuotedString(builderkey);
        builder.append("; filename=");
        appendQuotedString(builderfileName);
        builder.append();
        return StringUtils.utf8Bytes(builder.toString());
    }
    public ByteArrayEntity build(ProgressHandler progressHandlerCancellationHandler c) {
        try {
            .write();
        } catch (IOException e) {
            throw new AssertionError(e);
        }
        byte[] data = .toByteArray();
        ByteArrayEntity b = new ByteArrayEntity(dataprogressHandlerc);
        b.setContentType(new BasicHeader(
                HTTP.CONTENT_TYPE,
                "multipart/form-data; boundary=" + ));
        return b;
    }
New to GrepCode? Check out our FAQ X