URLConnection sometimes returns empty string response?
<p>I'm making an http GET request. It works in about 70% of my attempts. For some reason, I sometimes get no response string from a successful connection. I just setup a button in my app which keeps firing the code below. One call might fail to reply with a string, the next call works fine:</p>

<pre><code>private onButtonClick() {
    try {
        doit();
    } catch (Exception ex) {
        ...
    }
}   

public void doit() throws Exception {
    URL url = new URL("http://www.example.com/service");

    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setDoInput(true);
    connection.setUseCaches(false); 
    connection.setAllowUserInteraction(false); 
    connection.setReadTimeout(30 * 1000);
    connection.setRequestProperty("Connection", "Keep-Alive"); 
    connection.setRequestProperty("Authorization", 
        "Basic " +  Base64.encode("username" + ":" + "password"));

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

    String line = "";
    StringBuilder sb = new StringBuilder();
    while ((line = in.readLine()) != null) {
        sb.append(line);
    }
    in.close();

    connection.disconnect();

    // Every so often this prints an empty string!
    System.out.println(sb.toString());
}
</code></pre>

<p>am I doing something wrong here? It seems like maybe I'm not closing the connection properly from the last call somehow and the response gets mangled or something? I am also calling doit() from multiple threads simultaneously, but I thought the contents of the method are thread-safe, same behavior though,</p>

<p>Thanks</p>

<p>Thanks</p>
