在从blackberry应用程序中创建HttpConnection
之前,我想检查它是否已打开?因为没有检查当我尝试建立连接时我得到了class net.rim.device.api.io.ConnectionClosedException
。
编辑:发布OP答案的代码。
以下是我的http连接代码。
public String makePostRequest(String[] paramName, String[] paramValue) {
StringBuffer postData = new StringBuffer();
HttpConnection connection = null;
InputStream inputStream = null;
OutputStream out = null;
try {
connection = (HttpConnection) Connector.open(this.url);
connection.setRequestMethod(HttpConnection.POST);
for (int i = 0; i < paramName.length; i++) {
postData.append(paramName[i]);
postData.append("=");
postData.append(paramValue[i]);
postData.append("&");
}
String encodedData = postData.toString();
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", (new Integer(
encodedData.length())).toString());
connection.setRequestProperty("Cookie", Constants.COOKIE_TOKEN);
byte[] postDataByte = postData.toString().getBytes("UTF-8");
out = connection.openOutputStream();
out.write(postDataByte);
DebugScreen.Log("Output stream..."+out);
DebugScreen.Log("Output stream..."+connection.getResponseCode());
// get the response from the input stream..
inputStream = connection.openInputStream();
DebugScreen.Log("Input stream..."+inputStream);
byte[] data = IOUtilities.streamToBytes(inputStream);
response = new String(data);
} catch ( Exception e) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
WaitingScreen.removePopUP();
Status.show(Constants.CONNETION_ERROR);
}
});
DebugScreen.Log("Exception inside the make connection..makePostRequest."
+ e.getMessage());
DebugScreen.Log("Exception inside the make connection..makePostRequest."
+ e.getClass());
}finally {
try {
if(inputStream != null){
inputStream.close();
inputStream = null;
}
if(out != null){
out.close();
out = null;
}
if(connection != null){
connection.close();
connection = null;
}
} catch ( Exception ex) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
WaitingScreen.removePopUP();
}
});
DebugScreen.Log("Exception from the connection2 class.."
+ ex.getMessage());
DebugScreen.Log("Exception from the connection2 class.."
+ ex.getClass());
}
}
return response;
}
答案 0 :(得分:2)
在从blackberry应用程序进行httpconnection之前,我想检查它是否打开。
这没有意义。您希望在打开它之前确保它已打开。你不能。您必须尝试打开它,并在失败时处理异常。这就是例外情况。
测试任何资源是否可用的最佳方法是尝试使用它。你无法预测。你必须尝试一下。
因为没有检查当我试图建立连接时我得到了类net.rim.device.api.io.ConnectionClosedException。
所以它不可用。所以现在你知道了。这是正确的行为。你已经做对了。这里毫无疑问要回答。