我有一个计时器任务,它在触发时关闭连接,问题是有时它会在连接实际打开之前触发,如下所示:
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)
line: 484 且未找到源:S。
最佳答案
连接存在于不同的线程中,并且有自己的生命周期。您正在尝试以同步方式从计时器线程访问它。
首先,连接是一个状态机。它从“setup”状态开始,然后如果在其上调用某些方法(任何需要联系服务器的方法),则更改为“connected”状态,最后当连接已关闭时,它更改为“close”状态由服务器或客户端终止。 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.
如果确实需要在关闭后执行某些操作,请向连接传递一个“监听器”对象,以便它可以在连接关闭时回调,并传回响应代码(如果连接与服务器曾经建立过)。
关于blackberry - 超时关闭 Blackberry HttpConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15227034/