Android读取远程文本文件退出时出现意外的流结束

时间:2015-03-16 20:21:17

标签: android http

我从我的http服务器下载不同的媒体文件; mp3,jpg / png /和html。
当我使用现已弃用的HttpClient时,一切正常 我决定使用HttpURLConnection。

但是我遇到了文本文件(html)的问题 read()阻止小html文件,也许等待EOF或者我不知道什么,在几秒钟内退出并退出异常"意外结束流"。

我的代码是:

URL url = new URL(urlString);

postParams = String.format("registration=%s&"....);

urlConnection = (HttpURLConnection) url.openConnection();

urlConnection.setDoOutput(true); // It's a POST request which replies sending a file
urlConnection.setChunkedStreamingMode(0);
if (fileName.contains(".htm")) { // Tried this to see...
    urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
    urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + "UTF-8");
}

OutputStream output = urlConnection.getOutputStream();
output.write(postParams.getBytes("UTF-8"));

is = new BufferedInputStream(urlConnection.getInputStream());   

/* Get information from the HttpURLConnection automatically fires the request
 * http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests
 */
int status = urlConnection.getResponseCode();   

if (status == 200) {

    int len, size = 0;
    byte[] buf = new byte[128 * 1024];

    BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));

    try {
        while ((len = is.read(buf, 0, buf.length)) > 0) { 
            os.write(buf, 0, len);
            size += len;
        }
        os.flush();
    } catch (IOException e) {
        Log.d(Constants.APP_TAG, "IOException." + e); // HTML files end here after few seconds
    } finally {
        nbFilesDownloaded++;
        is.close();
        os.close();

        file.setReadable(true, false);
        file.setWritable(true, false);
    }
}

任何想法都可以解释为什么它不能正常退出read()??

  

编辑:我验证了导致此异常的html文件,我的网络服务器在标题中没有包含Content-Length。这可能是问题的原因吗?

1 个答案:

答案 0 :(得分:0)

尝试使用okhttp http://square.github.io/okhttp/。我已正确下载文件。我希望能帮到你。

保罗。