【发布时间】:2015-11-19 19:44:35
【问题描述】:
Android Studio 1.5
我已经构建了一个 java 库,我将其复制到 Android Studio 中。 java 库在我在 Linux 上运行的测试用例中运行正常。但是,当我将库复制到 Android Studio 并在实际设备上进行测试时。它无法读取所有 JSON。只有 ~half 被读取。 JSON 只有大约 15238 字节。但是,我还有其他较小的 JSON,大约 1000 字节,可以与此代码配合使用。
Android 是否有某种限制?
我正在使用httpUrlConnection 和POST
jsonString = readJSONInputStream(mHttpUrlconnection.getInputStream());
以及功能:
private String readJSONInputStream(InputStream inputStream) {
try {
final int SIZE = 8024;
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), SIZE);
String line = "";
String jsonString = "";
while((line = reader.readLine()) != null) {
jsonString += line;
}
log.log(Level.INFO, "JSONSTRING: " + jsonString);
/* Success */
return jsonString;
}
catch(...) {
.
}
}
我也试过用这个。这适用于我在 Linux 上的测试用例。但无法读取 Android 上的所有数据。
private String readJSONInputStream(InputStream inputStream) {
try {
String jsonString = IOUtils.toString(inputStream, "UTF-8");
/* Success */
return jsonString;
}
catch(...) {
.
}
}
使用 HttpUrlConnection 的代码
try {
URL url = null;
HttpsURLConnection connection = null;
OutputStreamWriter outputStream = null;
int responseCode = -1;
url = new URL(cnn_url);
connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=utf8");
connection.setRequestProperty("Accept", "application/json");
connection.setUseCaches(true);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(15000); /* msecs i.e. 15 seconds */
/* Send POST request with JSON object */
outputStream = new OutputStreamWriter(connection.getOutputStream());
outputStream.write(jsonObject.toString(), 0, jsonObject.toString().length());
outputStream.flush();
log.log(Level.INFO, "Connected to server OK");
/* Get response */
responseCode = connection.getResponseCode();
log.log(Level.INFO, "Returned responseCode [ " + responseCode + " ]");
String jsonString = null;
if(responseCode == 200) {
/* Read contents of inputstream into a string to be returned */
jsonString = readJSONInputStream(connection.getInputStream());
if(jsonString == null) {
log.log(Level.SEVERE, "Failed to read connection input stream");
}
else {
log.log(Level.INFO, "jsonString: " + jsonString);
}
}
else {
log.log(Level.SEVERE, "Invalid response code [ " + responseCode + " ]");
}
return jsonString;
}
当 JSON 小于 ~1000 字节时,这些函数可在 Android 上运行。但是对于我拥有的 ~15000 的大型 JSON,它只能读取 ~ 一半。当我打印输出时,我只看到一半的 JSON 字符串。
是不是我做错了什么?
【问题讨论】:
-
点击这个链接你总是将大数据发送到服务器使用 MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("头像", new ByteArrayBody(data,"pic.jpg" )); stackoverflow.com/questions/14027882/…
-
我没有发送大数据。但是收到一个大的 JSON。