在Android的发送Byte数组由httpost [英] Sending Byte array by httpost in Android

查看:174
本文介绍了在Android的发送Byte数组由httpost的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我previous试图用
<一href=\"http://stackoverflow.com/questions/4896949/android-httpclient-file-upload-data-corruption-and-timeout-issues/4896988#4896988\">Android HttpClient的文件上传数据损坏和超时问题

不过,我真的不知道如何使用它......

在我的项目,我$ pviously使用的NameValuePair名单将数据发送到Apache服务器的字符串输入p $如

在POST方法(DB_Packet是字符串变量)


  

列表的NameValuePair =新的ArrayList(2);

  nameValuePair.add(新BasicNameValuePair(内容,DB_Packet));
    nameValuePair.add(新BasicNameValuePair(guestbookName,默认));
 httpPost.setEntity(新UrlEn codedFormEntity(的NameValuePair));


不过,字符串变大尺寸(13MB)。我需要使用COM pression方法来压缩春。

这COM pression方法返回字节数组类型。因此,我需要字节数组发送到Apache服务器和我需要传递参数guestbookName,因为

我的JSP文件包含

 &LT;形式的行动=/标志的方法=后&GT;
  &LT; D​​IV&GT;&LT; textarea的名字=内容行=3COLS =60&GT;&LT; / textarea的&GT;&LT; / DIV&GT;
  &LT; D​​IV&GT;&LT;输入类型=提交值=邮政贺卡/&GT;&LT; / DIV&GT;
  &LT;输入类型=隐藏的名字=guestbookNameVALUE =默认/&GT;
&LT; /表及GT;

不过,我真的不知道该我可以发送字节数组服务器的功能。

什么功能,我需要用来发送(Paramenter,字节数组)?

和在服务器端


  

req.getParameter(内容)的getBytes();


才是正道哟得到字节数组?

感谢


解决方案

要送你需要使用的multipart / form-data编码的二进制数据。下面是一些例子code。这个类带codeS数据(包括字节数组 - 你可以扩展这个过于读取文件)

 包com。示例;进口java.io.IOException异常;
进口java.io.OutputStream中;
进口java.io.UnsupportedEncodingException;
进口java.net.URLEn codeR;
进口的java.util.ArrayList;
进口的java.util.List;公共类{的PostData    类ByteData {
        字节[]数据;
        串标头;
        字符串名称;        ByteData(字符串名称,字符串的contentType,字节[]数据){
            this.name =名称;
            this.data =数据;
            尝试{
                标题= - + +边界CRLF +内容处置:表格数据;名称= \\文件\\;文件名= \\+ URLEn coder.en code(名称,编码) +\\, + CRLF +
                        内容类型:+ +的contentType CRLF + CRLF;
            }赶上(UnsupportedEncodingException五){
                e.printStackTrace();
            }
        }        公众诠释的getSize(){
            返回header.length()+ data.length + CRLF.length();
        }
        公共无效的write(OutputStream的了)抛出IOException
            out.write(header.getBytes());
            out.write(数据);
            out.write(CRLF.getBytes());
        }
    }    私有静态最后弦乐TAG = PostData.class.getSimpleName();
    静态最后弦乐边界=3C3F786D6C2076657273696F6E2E302220656E636F64696E673D662D38223F3E0A3C6D616E6966;
    静态最后弦乐CRLF =\\ r \\ n;
    私人最终字符串编码;
    私人StringBuilder的SB;
    私人字符串拖车;
    私人列表&LT; ByteData&GT; DataList控件=新的ArrayList&LT; ByteData&GT;();
    公众的PostData(){
        这个(UTF-8);
    }    公众的PostData(字符串编码){
        this.encoding =编码;
        SB =新的StringBuilder();
        拖车= - +边界+ - + CRLF;
    }    公共字符串的getContentType(){
        返回的multipart / form-data的;边界=+界线;
    }    公共无效的addValue(字符串名称,int值){
        的addValue(名称,Integer.toString(值));
    }    公共无效的addValue(字符串名称,字符串值){
        sb.append( - +边界+ CRLF);
        sb.append(内容处置:表格数据;名称= \\);
        尝试{
            sb.append(URLEn coder.en code(名称,编码));
            sb.append('');
            sb.append(CRLF + CRLF);
            sb.append(值);
            sb.append(CRLF);
        }赶上(UnsupportedEncodingException五){
            e.printStackTrace();
        }
    }    公共无效addData(字符串名称,字符串的contentType,字节[]数据){
        dataList.add(新ByteData(姓名,则contentType,数据));
    }
    众长的getLength(){
        长长度= sb.toString()的getBytes()长度。
        长+ = trailer.length();
        对于(ByteData byteData:DataList控件)
            长+ = byteData.getSize();
        返回的长度;
    }    公共字符串的toString(){
        返回sb.toString();
    }    公共无效的write(OutputStream的了)抛出IOException
        out.write(sb.toString()的getBytes());
        对于(ByteData byteData:DataList控件)
            byteData.write(出);
        out.write(trailer.getBytes());
    }
}

本类打开一个连接并发送数据:

 包com。示例;进口java.io.BufferedOutputStream;
进口java.io.IOException异常;
进口java.io.OutputStream中;
进口java.net.HttpURLConnection中;
进口java.net.MalformedURLException;
进口的java.net.URL;公共类上传{    私有静态最终诠释CONNECTION_TIMEOUT = 10 * 1000;
    私有静态最终诠释READ_TIMEOUT = 10 * 1000;
    最终私人字符串协议;
    最终私人字符串服务器;    公共上传(协议字符串,字符串服务器){
        this.protocol =协议;
        this.server =服务器;
    }    保护HttpURLConnection的getBaseConnection(字符串终点)抛出IOException
        HttpURLConnection的连接;
        URL网址;        尝试{
            URL =新的URL(协议+://+服务器+/+终点);
            连接=(HttpURLConnection类)url.openConnection();
        }赶上(MalformedURLException的E){
            抛出新IOException异常(不正确的网址);
        }
        connection.setDoInput(真);
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        返回连接;
    }    公众诠释上传(字符串终点的PostData POSTDATA)抛出IOException
        HttpURLConnection的连接= NULL;        连接= getBaseConnection(终点);
        connection.setDoOutput(真);
        connection.setInstanceFollowRedirects(假);
        connection.setRequestMethod(POST);
        connection.setRequestProperty(字符集,UTF-8);
        connection.setRequestProperty(内容类型,postData.getContentType());
        connection.setRequestProperty(接受,文/ JSON);
        出的OutputStream =新的BufferedOutputStream(connection.getOutputStream(),8192);
        postData.write(出);
        了out.flush();
        INT响应= connection.getResponse code();
        connection.disconnect();
        返回响应;
        }
}

最后使用这些类的测试程序。

 包com。示例;
进口java.io.FileOutputStream中;
进口java.io.IOException异常;公共类UploadTest {    私有静态字节[]数据= {1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1};    静态公共无效的主要(字符串ARGS []){        PD的PostData =新的PostData();
        pd.addValue(用户,乔);
        pd.addValue(名,张三);
        pd.addData(binary_data,应用程序/八位字节流数据);
        上传上传=新上传(HTTP,本地主机);
        尝试{
            uploader.upload(upload.php的PD);
        }赶上(IOException异常五){
            e.printStackTrace();
        }
    }
}

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 how to use it......

In my project, I previously used list of NameValuePair to send String type of data to Apache server such as

In post method (DB_Packet is string variable)

List nameValuePair = new ArrayList(2);

  nameValuePair.add(new BasicNameValuePair("content", DB_Packet));
    nameValuePair.add(new BasicNameValuePair("guestbookName", "default"));
 httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair)); 

However, String becomes larger size ( 13mb). I needed to use compression method to zip the Spring.

This compression method is return "byte type array". Therefore, I need to send byte Array to Apache server and i need to pass parameter "guestbookName" because

my jsp file contains

   <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>

However, I am not really sure the the function which I can send byte array to server.

What function do i need to use to send ("Paramenter", "byte Array") ?

and in server side

req.getParameter("content").getBytes();

is the right way yo get byte array?

thanks

解决方案

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;

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

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;

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;
        }
}

Finally a test program using these classes.

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

这篇关于在Android的发送Byte数组由httpost的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆