Multipart/form-data Enctype Json For Android
I want to upload image and its information. I wanna to use multipart/ form data json for android. I have also seen this Stack Overflow question Android:How to upload .mp3 file and
Solution 1:
You can use this SimpleMultipartEntity class for sending Multipart data :
publicclassSimpleMultipartEntityimplementsHttpEntity {
private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
.toCharArray();
privateString boundary = null;
ByteArrayOutputStream out = newByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
publicSimpleMultipartEntity() {
final StringBuffer buf = newStringBuffer();
final Random rand = newRandom();
for (int i = 0; i < 30; i++) {
buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
}
this.boundary = buf.toString();
}
publicvoidwriteFirstBoundaryIfNeeds() {
if (!isSetFirst) {
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
e.printStackTrace();
}
}
isSetFirst = true;
}
publicvoidwriteLastBoundaryIfNeeds() {
if (isSetLast) {
return;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
e.printStackTrace();
}
isSetLast = true;
}
publicvoidaddPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
.getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
e.printStackTrace();
}
}
publicvoidaddPart(final String key, final String fileName,
final InputStream fin) {
addPart(key, fileName, fin, "application/octet-stream");
}
publicvoidaddPart(final String key, final String fileName,
final InputStream fin, Stringtype) {
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: " + type + "\r\n";
out.write(("Content-Disposition: form-data; name=\"" + key
+ "\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
e.printStackTrace();
} finally {
try {
fin.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
publicvoidaddPart(final String key, final File value) {
try {
addPart(key, value.getName(), newFileInputStream(value));
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
}
publicStringgetBoundary() {
return boundary;
}
publicvoidsetBoundary(String boundary) {
this.boundary = boundary;
}
@Overridepublic long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
@OverridepublicHeadergetContentType() {
returnnewBasicHeader("Content-Type", "multipart/form-data; boundary="
+ boundary);
}
@OverridepublicbooleanisChunked() {
returnfalse;
}
@OverridepublicbooleanisRepeatable() {
returnfalse;
}
@OverridepublicbooleanisStreaming() {
returnfalse;
}
@OverridepublicvoidwriteTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
@OverridepublicHeadergetContentEncoding() {
returnnull;
}
@OverridepublicvoidconsumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
thrownewUnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
@OverridepublicInputStreamgetContent() throws IOException,
UnsupportedOperationException {
returnnewByteArrayInputStream(out.toByteArray());
}
}
Usage :
StringserviceUri="service url";
InputStreamfileInputStream= mInputStream; //Your file streamStringfileName="your file name";
StringfileKey="Key name what server is looking for"
HashMap<String, String> headerparts = mHeaderParts; //Other header parts that you need to send along.HttpClienthttpClient=newDefaultHttpClient();
HttpPosthttpPost=newHttpPost(serviceUri);
SimpleMultipartEntityentity=newSimpleMultipartEntity();
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "multipart/form-data; boundary="
+ entity.getBoundary());
entity.writeFirstBoundaryIfNeeds();
if (headerparts != null) {
Object[] keySet = headerparts.keySet().toArray();
for (inti=0; i < keySet.length; i++) {
Stringkey= keySet[i].toString();
Stringvalue= headerparts.get(key);
entity.addPart(key, value);
}
}
entity.addPart(fileKey, fileName, fileInputStream);
entity.writeLastBoundaryIfNeeds();
httpPost.setEntity(entity);
try {
mResponse = httpClient.execute(httpPost);
} catch (Exception e) {
e.printStackTrace();
}
Post a Comment for "Multipart/form-data Enctype Json For Android"