我有一个 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/