【发布时间】:2014-05-07 05:05:00
【问题描述】:
我目前正在开发一个 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 和各种其他数字作为参数,但它没有改变任何东西。
提前感谢您的任何建议。
【问题讨论】:
-
在你的“readIt”中你的读取输入流只有一次,从缓冲区中获取一小块数据。您需要重复阅读直到结束。
标签: java android xml inputstream httpurlconnection