我目前正在开发 Android 应用程序并遇到以下问题。 我正在向服务器发出 HTTP 请求,该服务器应该将我返回的 XML 内容发送给我,然后我将对其进行解析。我注意到在解析长 XML 字符串时反复出现错误,因此我决定显示我的请求结果并发现我收到的字符串(或流?)被随机截断了。有时我会得到整个字符串,有时是一半,有时是三分之一,它似乎在被截断的字符数量上遵循某种模式,我的意思是有时我在请求后得到 320 个字符,然后在请求后得到 156 个字符接下来是 320 两次,然后是 156(这些不是实际数字,但它遵循一种模式)。
这是我的请求和将 InputStream 转换为字符串的代码:
private String downloadUrlGet(String myurl) throws IOException {
InputStream is = null;
// Only display the first 20000 characters of the retrieved
// web page content.
int len = 20000;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/xml");
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
// Reads an InputStream and converts it to a String.
private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
我尝试检索的 XML 的长度远小于 20000。 我尝试将 HttpURLConnection.setChunkedStreamingMode() 与 0 和其他各种数字一起用作参数,但它没有改变任何东西。
提前感谢您的任何建议。
最佳答案
您犯了一个常见的错误,即假设 read()
填充了缓冲区。请参阅Javadoc。它没有义务这样做。事实上,它没有义务传输超过一个字节。您需要循环读取,直到遇到流结束(read()
返回 -1)。
关于java - Android HttpUrlConnection 结果字符串被截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22700920/