Android while getting HTTP response to file how to know it wasn't fully loaded?

Posted by Stan on Stack Overflow See other posts from Stack Overflow or by Stan
Published on 2013-07-01T22:55:23Z Indexed on 2013/07/01 23:05 UTC
Read the original article Hit count: 155

Filed under:
|
|

I'm using this approach to store a big-sized response from server to parse it later:

final HttpClient client = new DefaultHttpClient(new BasicHttpParams());
final HttpGet mHttpGetRequest = new HttpGet(strUrl);
mHttpGetRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
FileOutputStream fos = null;
try {
    final HttpResponse response = client.execute(mHttpGetRequest);
    final StatusLine statusLine = response.getStatusLine();
    lastHttpErrorCode = statusLine.getStatusCode();
    lastHttpErrorMsg = statusLine.getReasonPhrase();
    if (lastHttpErrorCode == 200) {
        HttpEntity entity = response.getEntity();
        fos = new FileOutputStream(reponseFile);
        entity.writeTo(fos);
        entity.consumeContent();
        fos.flush();
    }
} catch (ClientProtocolException e) {
    e.printStackTrace();
    lastHttpErrorMsg = e.toString();
    return null;
}
catch (final ParseException e) {
    e.printStackTrace();
    lastHttpErrorMsg = e.toString();
    return null;
}
catch (final UnknownHostException e) {
    e.printStackTrace();
    lastHttpErrorMsg = e.toString();
    return null;    
}
catch (IOException e) {
    e.printStackTrace();
    lastHttpErrorMsg = e.toString();
} finally{
    if (fos!=null)
        try{
            fos.close();
        } catch (IOException e){}
}

now how could I ensure the response was completely received and thus saved to file?
Assume client's device lost Internet connection while this code was running. So the app received only some part of real response. And I'm pretty sure it happens cuz I got parsing exceptions like "tag not closed", "unexpected end of file" etc. So I need to detect somehow this situation to prevent code from parsing partial response but can't see how. Is it possible at all and how to do it? Or has it has to raise IOException in such cases?

© Stack Overflow or respective owner

Related posts about android

Related posts about file