HttpURLConnection.getResponseCode() returns -1 on second invocation

Try set this property to see if it helps,

http.keepAlive=false

I saw similar problems when server response is not understood by UrlConnection and client/server gets out of sync.

If this solves your problem, you have to get a HTTP trace to see exactly what’s special about the response.

EDIT: This change just confirms my suspicion. It doesn’t solve your problem. It just hides the symptom.

If the response from first request is 200, we need a trace. I normally use Ethereal/Wireshark to get the TCP trace.

If your first response is not 200, I do see a problem in your code. With OAuth, the error response (401) actually returns data, which includes ProblemAdvice, Signature Base String etc to help you debug. You need to read everything from error stream. Otherwise, it’s going to confuse next connection and that’s the cause of -1. Following example shows you how to handle errors correctly,

public static String get(String url) throws IOException {

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    URLConnection conn=null;
    byte[] buf = new byte[4096];

    try {
        URL a = new URL(url);
        conn = a.openConnection();
        InputStream is = conn.getInputStream();
        int ret = 0;
        while ((ret = is.read(buf)) > 0) {
            os.write(buf, 0, ret);
        }
        // close the inputstream
        is.close();
        return new String(os.toByteArray());
    } catch (IOException e) {
        try {
            int respCode = ((HttpURLConnection)conn).getResponseCode();
            InputStream es = ((HttpURLConnection)conn).getErrorStream();
            int ret = 0;
            // read the response body
            while ((ret = es.read(buf)) > 0) {
                os.write(buf, 0, ret);
            }
            // close the errorstream
            es.close();
            return "Error response " + respCode + ": " + 
               new String(os.toByteArray());
        } catch(IOException ex) {
            throw ex;
        }
    }
}

Leave a Comment