I am currently developing an Android application and am facing the following problem. I am making an HTTP request to a server which should send me the XML content, which I then parse. I noticed repeated errors while parsing long XML strings, so I decided to display the result of my queries and found that the string (or stream?) That I get was randomly truncated. Sometimes I get a whole line, sometimes half, and sometimes a third, and it seems that it matches a certain pattern in the number of truncated characters, which I mean is that sometimes I get 320 characters after the request, after which then 320, then again 156 (these are not actual numbers, but follow the pattern).
Here is my code for querying and converting an InputStream to a string:
private String downloadUrlGet(String myurl) throws IOException {
InputStream is = null;
int len = 20000;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 );
conn.setConnectTimeout(15000 );
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/xml");
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
String contentAsString = readIt(is, len);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
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);
}
The length of the XML I'm trying to get is much less than 20,000. I tried using HttpURLConnection.setChunkedStreamingMode () with 0 and various other numbers as a parameter, but didn't change anything.
Thanks in advance for any suggestions.
source
share