java - 如何在 http 连接上写入大型 JSON 数组

标签 java android

我有一个 JSON 数组,它进一步包含许多 JSON 对象,我想将这个 JSON 数组作为字符串发布到 http post 连接上。我的问题是,当我将 JSON 数组转换为字符串时,字符串变量仅包含 JSON 数组数据的子集(由于 String 变量的大小限制)。结果我发布了不完整的 JSON 数组。在 http 连接上发布大型 JSON 数组的解决方案是什么。下面的代码将 JSON 数组转换为字符串。

JSONArray jsonArray = new JSONArray();
jsonArray .toString();

最佳答案

使用 HttpURLConnection ( http://developer.android.com/reference/java/net/HttpURLConnection.html ) 开发人员文档明确表示

An URLConnection for HTTP (RFC 2616) used to send and receive data over the web. Data may be of any type and length. This class may be used to send and receive streaming data whose length is not known in advance.

发布查询的示例代码:

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
 urlConnection.setDoOutput(true);
 urlConnection.setChunkedStreamingMode(0);

 OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
 writeStream(out); // read data from db and write it to stream

 InputStream in = new BufferedInputStream(urlConnection.getInputStream());
 readStream(in);
finally {
 urlConnection.disconnect();
}
}

writeStream(OutputStream out) {
  while (read all records from db) {
     byte[] bytes = record.getBytes("UTF-8");
     out.write(bytes);
  }
}

在 AsycTask doInBackground 方法中使用上述代码。从数据库中读取所有记录并添加到函数 writeStream 中的输出流。使用此方法,您的字符串变量在任何时候都将只包含一条记录。

关于java - 如何在 http 连接上写入大型 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27520541/

相关文章:

java - 在 Java 中混合组合和继承

Android - 尝试在启动时测试服务(java.lang.SecurityException : Permission Denial)

android - 添加aar时只支持Jar类型的本地依赖

android - 在android中从手机打印数据

Java:客户端、客户端、(线程)服务器、流客户端信息、JPanel 创建但消息(?)阻止游戏开始

java - Maven 编译器插件错误 : can't access enum (bad signature, bad class)

java - 具有模式的 SimpleDateFormat 会导致错误 Unparseable Date

Java 和处理 3.0 “frame” 类已弃用,是否有替代方案?

android - 在Android上读取MIFARE Classic卡时如何防止 key 泄露?

android - 位图回收Android