当前位置: 首页 > 知识库问答 >
问题:

在Android中通过httpost发送字节数组

郭子航
2023-03-14

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

我以前试图使用Android httpclient文件上传数据损坏和超时问题

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

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

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

list name value pair = new ArrayList(2);

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

但是,字符串变得更大 ( 13mb)。我需要使用压缩方法来压缩Spring。

此压缩方法返回“字节类型数组”。因此,我需要将字节数组发送到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>

但是,我不太确定我可以向服务器发送字节数组的函数

我需要用什么函数来发送(“Paramenter”,“字节数组”)?

在服务器端

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

这是得到字节数组的正确方法吗?

谢谢

共有1个答案

白越
2023-03-14

要发送二进制数据,您需要使用多部分/格式数据编码。下面是一些示例代码。这个类编码数据(包括字节数组——你也可以扩展它来读取文件)

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();
        }
    }
}
 类似资料:
  • 问题内容: 通过连接到外部BLE设备,我最多可以发送20个字节的数据。如何发送大于20个字节的数据。我已经读到我们必须将数据分段或将特征拆分为所需的部分。如果我假设我的数据是32字节,你能否告诉我我需要在代码中进行的更改才能使其正常工作?以下是我的代码中必需的摘录: 这是我用于发送数据的代码。在以下onclick事件中使用“发送”功能。 当大于20个字节时,则仅接收前20个字节。如何纠正呢? 为了

  • 我需要通过Java socket发送一个文本消息到服务器,然后发送一个字节数组,然后是一个字符串等等。到目前为止,我所开发的内容还在工作,但客户端只读取发送的第一个字符串。 从服务器端:我使用发送字节数组,使用发送字符串。 问题是客户机和服务器不同步,我的意思是服务器发送字符串然后字节数组然后字符串,而不等待客户机消耗每个需要的字节。 我的意思是情况不是这样的:

  • 我有一个数组类型的。我必须在python中通过流/TCP套接字发送它。然后我必须在接收端接收相同的阵列。

  • 出于某些原因,我需要通过服务器套接字分别发送多个字节数组,客户端套接字将接收这些字节数组。发送字节数组后,发现客户端套接字接收的字节数组与服务器套接字接收的字节数组不相等。如果我使用ObjectOutputStream和ObjectInputStream,那么一切都很好,但是根据我的需要,我不能使用ObjectOutputStream和ObjectInputStream,因为我的服务器需要连接两个

  • 问题内容: 有人可以演示如何使用Java通过TCP连接从发送方程序向接收方程序发送字节数组。 (我是Java编程的新手,似乎找不到如何显示连接两端(发送方和接收方)的示例。)如果您知道现有示例,则可以发布链接。(无需重新发明轮子。)PS这 不是 功课!:-) 问题答案: Java中的和类本机处理字节数组。您可能要添加的一件事是消息开头的长度,以便接收方知道期望多少字节。我通常喜欢提供一种方法,该方

  • 问题内容: 我如何使用getOutputStream方法发送一个strin。正如他们提到的,它只能发送字节。到目前为止,我可以发送一个字节。但不是字符串值。 提前致谢 问题答案: 如何使用PrintWriter: 编辑 :找到了我自己的答案,看到讨论了一个改进,但未列出。这是使用OutputStreamWriter编写字符串的更好方法: