Skip to content Skip to sidebar Skip to footer

Sending Byte Array By Httpost In Android

I have a question about sending byte array in Android. i previous tried to use Android httpclient file upload data corruption and timeout issues but, i didn't really understand ho

Solution 1:

To send binary data you need to use multipart/form-data encoding. Here is some example code. This class encodes data (including byte arrays - you could extend this to read files too)

package com.example;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

publicclassPostData {

    classByteData {
        byte[] data;
        String header;
        String name;

        ByteData(String name, String contentType, byte[] data) {
            this.name = name;
            this.data = data;
            try {
                header = "--" + BOUNDARY + CRLF + "Content-Disposition: form-data; name=\"file\"; filename=\"" + URLEncoder.encode(name, encoding) + "\";" + CRLF +
                        "Content-Type: " + contentType + CRLF + CRLF;
            } catch(UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        publicintgetSize() {
            return header.length() + data.length + CRLF.length();
        }


        publicvoidwrite(OutputStream out)throws IOException {
            out.write(header.getBytes());
            out.write(data);
            out.write(CRLF.getBytes());
        }
    }

    privatestaticfinalStringTAG= PostData.class.getSimpleName();
    staticfinalStringBOUNDARY="3C3F786D6C2076657273696F6E2E302220656E636F64696E673D662D38223F3E0A3C6D616E6966";
    staticfinalStringCRLF="\r\n";
    privatefinal String encoding;
    private StringBuilder sb;
    private String trailer;
    private List<ByteData> dataList = newArrayList<ByteData>();


    publicPostData() {
        this("UTF-8");
    }

    publicPostData(String encoding) {
        this.encoding = encoding;
        sb = newStringBuilder();
        trailer = "--" + BOUNDARY + "--" + CRLF;
    }

    public String getContentType() {
        return"multipart/form-data; boundary=" + BOUNDARY;
    }

    publicvoidaddValue(String name, int value) {
        addValue(name, Integer.toString(value));
    }

    publicvoidaddValue(String name, String value) {
        sb.append("--" + BOUNDARY + CRLF);
        sb.append("Content-Disposition: form-data; name=\"");
        try {
            sb.append(URLEncoder.encode(name, encoding));
            sb.append('"');
            sb.append(CRLF + CRLF);
            sb.append(value);
            sb.append(CRLF);
        } catch(UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    publicvoidaddData(String name, String contentType, byte[] data) {
        dataList.add(newByteData(name, contentType, data));
    }


    publiclonggetLength() {
        longlength= sb.toString().getBytes().length;
        length += trailer.length();
        for(ByteData byteData : dataList)
            length += byteData.getSize();
        return length;
    }

    public String toString() {
        return sb.toString();
    }

    publicvoidwrite(OutputStream out)throws IOException {
        out.write(sb.toString().getBytes());
        for(ByteData byteData : dataList)
            byteData.write(out);
        out.write(trailer.getBytes());
    }
}

This class opens a connection and sends data:

package com.example;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

publicclassUploader {

    privatestaticfinalintCONNECTION_TIMEOUT=10 * 1000;
    privatestaticfinalintREAD_TIMEOUT=10 * 1000;
    finalprivate String protocol;
    finalprivate String server;

    publicUploader(String protocol, String server) {
        this.protocol = protocol;
        this.server = server;
    }

    protected HttpURLConnection getBaseConnection(String endpoint)throws IOException {
        HttpURLConnection connection;
        URL url;

        try {
            url = newURL(protocol + "://" + server + "/" + endpoint);
            connection = (HttpURLConnection)url.openConnection();
        } catch(MalformedURLException e) {
            thrownewIOException("Malformed URL");
        }
        connection.setDoInput(true);
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        return connection;
    }

    publicintupload(String endpoint, PostData postData)throws IOException {
        HttpURLConnectionconnection=null;

        connection = getBaseConnection(endpoint);
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Charset", "utf-8");
        connection.setRequestProperty("Content-Type", postData.getContentType());
        connection.setRequestProperty("Accept", "text/json");
        OutputStreamout=newBufferedOutputStream(connection.getOutputStream(), 8192);
        postData.write(out);
        out.flush();
        intresponse= connection.getResponseCode();
        connection.disconnect();
        return response;
        }
}

Finally a test program using these classes.

package com.example;


import java.io.FileOutputStream;
import java.io.IOException;

publicclassUploadTest {

    privatestaticbyte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5 , 4, 3, 2, 1};

    staticpublicvoidmain(String args[]) {

        PostDatapd=newPostData();
        pd.addValue("user", "joe");
        pd.addValue("name", "Joe Smith");
        pd.addData("binary_data", "application/octet-stream", data);
        Uploaderuploader=newUploader("http", "localhost");
        try {
            uploader.upload("upload.php", pd);
        } catch(IOException e) {
            e.printStackTrace();
        }
    }
}

Post a Comment for "Sending Byte Array By Httpost In Android"