1 30 package org.apache.commons.httpclient.methods.multipart; 31 32 import java.io.IOException ; 33 import java.io.OutputStream ; 34 import java.util.Random ; 35 36 import org.apache.commons.httpclient.methods.RequestEntity; 37 import org.apache.commons.httpclient.params.HttpMethodParams; 38 import org.apache.commons.httpclient.util.EncodingUtil; 39 import org.apache.commons.logging.Log; 40 import org.apache.commons.logging.LogFactory; 41 42 77 public class MultipartRequestEntity implements RequestEntity { 78 79 private static final Log log = LogFactory.getLog(MultipartRequestEntity.class); 80 81 82 private static final String MULTIPART_FORM_CONTENT_TYPE = "multipart/form-data"; 83 84 87 private static byte[] MULTIPART_CHARS = EncodingUtil.getAsciiBytes( 88 "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); 89 90 94 private static byte[] generateMultipartBoundary() { 95 Random rand = new Random (); 96 byte[] bytes = new byte[rand.nextInt(11) + 30]; for (int i = 0; i < bytes.length; i++) { 98 bytes[i] = MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]; 99 } 100 return bytes; 101 } 102 103 104 protected Part[] parts; 105 106 private byte[] multipartBoundary; 107 108 private HttpMethodParams params; 109 110 115 public MultipartRequestEntity(Part[] parts, HttpMethodParams params) { 116 if (parts == null) { 117 throw new IllegalArgumentException ("parts cannot be null"); 118 } 119 if (params == null) { 120 throw new IllegalArgumentException ("params cannot be null"); 121 } 122 this.parts = parts; 123 this.params = params; 124 } 125 126 135 protected byte[] getMultipartBoundary() { 136 if (multipartBoundary == null) { 137 String temp = (String ) params.getParameter(HttpMethodParams.MULTIPART_BOUNDARY); 138 if (temp != null) { 139 multipartBoundary = EncodingUtil.getAsciiBytes(temp); 140 } else { 141 multipartBoundary = generateMultipartBoundary(); 142 } 143 } 144 return multipartBoundary; 145 } 146 147 151 public boolean isRepeatable() { 152 for (int i = 0; i < parts.length; i++) { 153 if (!parts[i].isRepeatable()) { 154 return false; 155 } 156 } 157 return true; 158 } 159 160 163 public void writeRequest(OutputStream out) throws IOException { 164 Part.sendParts(out, parts, getMultipartBoundary()); 165 } 166 167 170 public long getContentLength() { 171 try { 172 return Part.getLengthOfParts(parts, getMultipartBoundary()); 173 } catch (Exception e) { 174 log.error("An exception occurred while getting the length of the parts", e); 175 return 0; 176 } 177 } 178 179 182 public String getContentType() { 183 StringBuffer buffer = new StringBuffer (MULTIPART_FORM_CONTENT_TYPE); 184 buffer.append("; boundary="); 185 buffer.append(EncodingUtil.getAsciiString(getMultipartBoundary())); 186 return buffer.toString(); 187 } 188 189 } 190 | Popular Tags |