2013-03-05 110 views
2

我有一个关闭时,它的触发连接的计时器任务,问题是,有时连接实际上是打开之前被触发,这样的:关闭黑莓的HttpConnection上超时

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? 
} 

当我尝试conn.getResponseCode(),抛出一个异常,但不是这样,为什么?

我得到这个错误:ClientProtocol(HttpProtocolBase).transitionToState(int)行:484和未找到源:S。

+1

下面的帖子很好地解释了这种情况,建议尝试在关闭连接之前获取responseCode或读取输入流。 – 2013-03-05 18:19:38

回答

2

连接生活在不同的线程中,并有其自己的生命周期。您正尝试以同步方式从计时器线程访问它。

首先,连接是一个状态机。它在“setup”状态下启动,如果调用某些方法(任何需要联系服务器的方法),则会切换到“connected”状态,最后当连接已经变为“closed”状态时由服务器或客户端终止。方法getResponseCode是那些可能导致连接从所谓的“设置”状态转换到“连接”状态(如果它尚未连接)的方法之一。您正试图立即获取响应代码,而无需知道连接是否已建立。您甚至不会让连接时间正确连接或关闭。即使你可以,看看什么样的javadoc说的close方法:

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

如果你真的需要它已被关闭后做一些事情,通过一个“监听器”对象的连接,以便它可以在连接关闭后回拨,并返回响应代码(如果与服务器的连接已建立)。