java – Android HttpUrlConnection结果字符串被截断

我目前正在开发
Android应用程序并遇到以下问题.

我正在向服务器发出一个HTTP请求,该服务器应该向我发回我随后解析的XML内容.我在解析长XML字符串时发现了重复出现的错误,因此我决定显示请求的结果,并发现我收到的字符串(或流?)是随机截断的.有时我得到整个字符串,有时是一半,有时是三分之一,它似乎遵循截断的字符数量中的某个模式,我的意思是我有时在请求之后获得320个字符然后在然后是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).

点赞