HttpUrlConnection accelerated output string for Android

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;
    // 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);
}

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.

+4
source share
1 answer

You make the usual mistake of believing that it read()fills the buffer. See Javadoc. He does not have to do this. Actually it is not necessary to transfer more than one byte. You need to read in the loop until you meet the end of the stream ( read()returns -1).

+1
source

Source: https://habr.com/ru/post/1533812/


All Articles