In my project for Blackberry 4.5, I create HttpConnection via Connector.open. If I connect over MDS, I can specify ConnectionTimeout in additional params to my URL. How can I specify timeouts if using direct TCP connection or TCP over WiFi?
+2
A:
According to this KB article, it's not possible to specify a connection timeout value for transports other than MDS.
Marc Novakowski
2010-03-05 17:14:11
Yes, i know this. What solutions you use to solve this?
Yeti
2010-03-07 18:45:55
You could set a TimerTask to execute after a period of time and check to see if the connection has been made or not. If it hasn't been made, then just abort and continue with your other code (or retry).
Marc Novakowski
2010-03-07 23:18:30
Also we can use two threads: one with loop for waiting subthread, and subthread where we try to open connection (or read data or smth else).
Yeti
2010-03-09 21:29:54
A:
In some cases it's possible to use Http over Socket and SocketConnectionEnhanced with READ_TIMEOUT option:
public class HTTPSocketConnector
{
static public String getHtml( String url, long timeout )
{
String response = "";
try
{
String host = getHostUrl( url );
String page = getPageUrl( url );
SocketConnectionEnhanced hc =
( SocketConnectionEnhanced )Connector.open( "socket://"
+ host + ":80" );
hc.setSocketOptionEx( SocketConnectionEnhanced.READ_TIMEOUT,
timeout );
DataOutputStream dout = new DataOutputStream(
( ( SocketConnection )hc ).openOutputStream() );
ByteArrayOutputStream bos = new ByteArrayOutputStream();
String request = "GET /" + page + " HTTP/1.1\r\n" + "Host: "
+ host + ":80\r\n" + "User-Agent: MIDP2.0\r\n"
+ "Content-Type: text/html\r\n\r\n";
bos.write( request.getBytes() );
dout.write( bos.toByteArray() );
dout.flush();
dout.close();
InputStream is = ( ( SocketConnection )hc ).openInputStream();
byte[] bytes = null;
bytes = IOUtilities.streamToBytes( is );
is.close();
response = new String( bytes, "UTF-8" );
}
catch( Exception e )
{
response = e.getMessage();
}
return response;
}
private static String getPageUrl( String url )
{
String result = url;
if( result.indexOf( "//" ) != -1 )
{
result = result.substring( result.indexOf( "//" )
+ "//".length(), result.length() );
}
if( result.indexOf( "/" ) != -1 )
{
result = result.substring( result.indexOf( "/" )
+ "/".length(), result.length() );
}
return result;
}
private static String getHostUrl( String url )
{
String result = url;
if( result.indexOf( "//" ) != -1 )
{
result = result.substring( result.indexOf( "//" )
+ "//".length(), result.length() );
}
if( result.indexOf( "/" ) != -1 )
{
result = result.substring( 0, result.indexOf( "/" ) );
}
return result;
}
}
Max Gontar
2010-03-09 14:28:51