Android Open Source - android-http Simple Multipart Entity






From Project

Back to project page android-http.

License

The source code is released under:

Apache License

If you think the Android project android-http listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*
    Android Asynchronous Http Client//from  w  ww . j a va 2s .c o  m
    Copyright (c) 2011 James Smith <james@loopj.com>
    http://loopj.com

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

/*
    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.loopj.android.http;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;

class SimpleMultipartEntity implements HttpEntity {
    private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

    private String boundary = null;

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    boolean isSetLast = false;
    boolean isSetFirst = false;

    public SimpleMultipartEntity() {
        final StringBuffer buf = new StringBuffer();
        final Random rand = new Random();
        for (int i = 0; i < 30; i++) {
            buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
        }
        this.boundary = buf.toString();

    }

    public void writeFirstBoundaryIfNeeds(){
        if(!isSetFirst){
            writeBoundary();
        }

        isSetFirst = true;
    }

    public void writeBoundary() {
        try {
            out.write(("--" + boundary + "\r\n").getBytes());
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }

    public void writeLastBoundaryIfNeeds() {
        if(isSetLast){
            return;
        }

        try {
            out.write(("--" + boundary + "--\r\n").getBytes());
            out.flush();
        } catch (final IOException e) {
            e.printStackTrace();
        }
        
        isSetLast = true;
    }

    public void addPart(final String key, final String value, final String contentType) {
        writeBoundary();
        try {
            out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
            out.write(("Content-Type: " + contentType + "\r\n\r\n").getBytes());
            out.write(value.getBytes());
            out.write(("\r\n").getBytes());
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }

    public void addPart(final String key, final String value) {
        addPart(key,value,"text/plain; charset=UTF-8");
    }

    public void addPart(final String key, final String fileName, final InputStream fin, final boolean isLast){
        addPart(key, fileName, fin, "application/octet-stream", isLast);
    }

    public void addPart(final String key, final String fileName, final InputStream fin, String type, final boolean isLast){
        writeBoundary();
        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.write(("\r\n").getBytes());
            
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fin.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void addPart(final String key, final File value, final boolean isLast) {
        try {
            addPart(key, value.getName(), new FileInputStream(value), isLast);
        } catch (final FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public long getContentLength() {
        writeLastBoundaryIfNeeds();
        return out.toByteArray().length;
    }

    @Override
    public Header getContentType() {
        return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    }

    @Override
    public boolean isChunked() {
        return false;
    }

    @Override
    public boolean isRepeatable() {
        return false;
    }

    @Override
    public boolean isStreaming() {
        return false;
    }

    @Override
    public void writeTo(final OutputStream outstream) throws IOException {
        writeLastBoundaryIfNeeds();
        outstream.write(out.toByteArray());
    }

    @Override
    public Header getContentEncoding() {
        return null;
    }

    @Override
    public void consumeContent() throws IOException,
    UnsupportedOperationException {
        if (isStreaming()) {
            throw new UnsupportedOperationException(
            "Streaming entity does not implement #consumeContent()");
        }
    }

    @Override
    public InputStream getContent() throws IOException,
    UnsupportedOperationException {
      writeLastBoundaryIfNeeds();
        return new ByteArrayInputStream(out.toByteArray());
    }
}




Java Source Code List

com.example.loopj.ExampleUsage.java
com.example.loopj.TwitterRestClientUsage.java
com.example.loopj.TwitterRestClient.java
com.example.markom.CustomCollectionLoaderActivity.java
com.example.markom.CustomObjectLoaderActivity.java
com.example.markom.ExampleHandlersActivity.java
com.example.markom.MainActivity.java
com.example.markom.RawResponseLoaderActivty.java
com.example.markom.TestUrls.java
com.example.markom.http.handler.CustomClassHandler.java
com.example.markom.http.handler.CustomGenericHandler.java
com.example.markom.http.loader.CustomClassLoader.java
com.example.markom.http.loader.CustomGenericLoader.java
com.example.markom.http.schema.CustomServiceResponse.java
com.example.markom.http.schema.Meta.java
com.example.markom.http.schema.Pagination.java
com.example.markom.model.Person.java
com.loopj.android.http.AsyncHttpClient.java
com.loopj.android.http.AsyncHttpRequest.java
com.loopj.android.http.AsyncHttpResponseHandler.java
com.loopj.android.http.BinaryHttpResponseHandler.java
com.loopj.android.http.JsonHttpResponseHandler.java
com.loopj.android.http.PersistentCookieStore.java
com.loopj.android.http.RequestParams.java
com.loopj.android.http.RetryHandler.java
com.loopj.android.http.SerializableCookie.java
com.loopj.android.http.SimpleMultipartEntity.java
com.loopj.android.http.SyncHttpClient.java
com.markom.android.http.exceptions.GsonParsingException.java
com.markom.android.http.exceptions.ParsingNotImplementedException.java
com.markom.android.http.handler.BaseClassHandler.java
com.markom.android.http.handler.BaseGenericHandler.java
com.markom.android.http.handler.BaseGsonHandler.java
com.markom.android.http.loader.BaseClassLoader.java
com.markom.android.http.loader.BaseGenericLoader.java
com.markom.android.http.loader.BaseGsonLoader.java
com.markom.android.http.loader.LoaderResponse.java
com.markom.android.http.loader.RawResponseLoader.java
com.markom.android.http.model.HttpMethod.java
com.markom.android.http.model.ServiceResponse.java
com.markom.android.http.parser.GSONParser.java