문제

I have a timer task that closes a connection when it's triggered, the problem is that sometimes it is triggered before the connection actually opens, like this:

try {
    HttpConnection conn = getMyConnection(); // Asume this returns a valid connection object

    // ... At this moment the timer triggers the worker wich closes the connection:
    conn.close(); // This is done by the timeTask before conn.getResponseCode()

    int mCode = conn.getResponseCode(); // BOOOMMMM!!!! EXPLOTION!!!!

    // ... Rest of my code here.

} catch(Throwable e) {
    System.out.println("ups..."); // This never gets called... Why?
}

When I try conn.getResponseCode(), an exception is thrown but isn't cought, why?

I get this error: ClientProtocol(HttpProtocolBase).transitionToState(int) line: 484 and a source not found :S.

도움이 되었습니까?

해결책

The connection lives in a different thread, and has its own lifecycle. You are trying to access it from the timer thread in a synchronous way.

To begin with, a connection is a state machine. It starts in the "setup" state, then changes to the "connected" state if some methods are called on it (any method that requires to contact the server), and finally it changes to the "closed" state when the connection has been terminated by either the server or the client. The method getResponseCode is one of those that can cause the connection to transition from the so called "setup" state to the "connected" state, if it wasn't already connected. You are trying to get the response code immediatly without even knowing whether the connection was established or not. You are not even letting the connection time to connect or close itself properly. Even if you could, have a look at what the javadocs say about the close method:

When a connection has been closed, access to any of its methods except this close() will cause an an IOException to be thrown.

If you really need to do something after it has been closed, pass a "listener" object to the connection so that it can call back when the connection has been closed, and pass back the response code (if the connection with the server was ever stablished).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top