Java Android中httpost发送字节数组

Java Android中httpost发送字节数组,java,android,http-post,bytearray,Java,Android,Http Post,Bytearray,我有一个关于在Android中发送字节数组的问题 我以前试过用 但是,我真的不知道如何使用它 在我的项目中,我以前使用NameValuePair列表将字符串类型的数据发送到Apache服务器,例如 In-post方法(DB_数据包是字符串变量) List nameValuePair=新的ArrayList(2) 但是,字符串变大了(13mb)。我需要使用压缩方法来压缩弹簧 此压缩方法返回“字节类型数组”。所以,我需要将字节数组发送到Apache服务器,并需要传递参数“guestbookName

我有一个关于在Android中发送字节数组的问题

我以前试过用

但是,我真的不知道如何使用它

在我的项目中,我以前使用NameValuePair列表将字符串类型的数据发送到Apache服务器,例如

In-post方法(DB_数据包是字符串变量)

List nameValuePair=新的ArrayList(2)

但是,字符串变大了(13mb)。我需要使用压缩方法来压缩弹簧

此压缩方法返回“字节类型数组”。所以,我需要将字节数组发送到Apache服务器,并需要传递参数“guestbookName”,因为

我的jsp文件包含

   <form action="/sign" method="post">
  <div><textarea name="content" rows="3" cols="60"></textarea></div>
  <div><input type="submit" value="Post Greeting" /></div>
  <input type="hidden" name="guestbookName" value="default"/>
</form>

然而,我并不确定我可以向服务器发送字节数组的函数

我需要使用什么函数发送(“参数”、“字节数组”)?

在服务器端

req.getParameter(“内容”).getBytes()

获取字节数组的正确方法是什么


感谢

要发送二进制数据,您需要使用多部分/表单数据编码。下面是一些示例代码。这个类对数据进行编码(包括字节数组-您也可以将其扩展为读取文件)

最后,使用这些类编写一个测试程序

package com.example;


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

public class UploadTest {

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

    static public void main(String args[]) {

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

通常的方法是将字节数组base64.BevynQ//谢谢您的快速回答。我试图使用base64,但它无法编译代码。我需要导入额外的jar才能使用base64吗?谢谢你使用android.util.Base64吗?我只是换成“org.apache.commons.codec.binary.Base64;”这是正确的软件包吗?应该没问题。它是一个第三方库,因此jar确实需要包含在构建中。
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;

public class PostData {

    class ByteData {
        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();
            }
        }

        public int getSize() {
            return header.length() + data.length + CRLF.length();
        }


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

    private static final String TAG = PostData.class.getSimpleName();
    static final String BOUNDARY = "3C3F786D6C2076657273696F6E2E302220656E636F64696E673D662D38223F3E0A3C6D616E6966";
    static final String CRLF = "\r\n";
    private final String encoding;
    private StringBuilder sb;
    private String trailer;
    private List<ByteData> dataList = new ArrayList<ByteData>();


    public PostData() {
        this("UTF-8");
    }

    public PostData(String encoding) {
        this.encoding = encoding;
        sb = new StringBuilder();
        trailer = "--" + BOUNDARY + "--" + CRLF;
    }

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

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

    public void addValue(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();
        }
    }

    public void addData(String name, String contentType, byte[] data) {
        dataList.add(new ByteData(name, contentType, data));
    }


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

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

    public void write(OutputStream out) throws IOException {
        out.write(sb.toString().getBytes());
        for(ByteData byteData : dataList)
            byteData.write(out);
        out.write(trailer.getBytes());
    }
}
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;

public class Uploader {

    private static final int CONNECTION_TIMEOUT = 10 * 1000;
    private static final int READ_TIMEOUT = 10 * 1000;
    final private String protocol;
    final private String server;

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

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

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

    public int upload(String endpoint, PostData postData) throws IOException {
        HttpURLConnection connection = 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");
        OutputStream out = new BufferedOutputStream(connection.getOutputStream(), 8192);
        postData.write(out);
        out.flush();
        int response = connection.getResponseCode();
        connection.disconnect();
        return response;
        }
}
package com.example;


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

public class UploadTest {

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

    static public void main(String args[]) {

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