我目前正在开发一个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)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句