Monday, August 24, 2009

How to use HTTP connection instead of a stream socket

This J2ME tips illustrates a method of using HHTP connection instead of a stream socket. This code looks very similar to the socket code, but there is a striking difference. The socket code first opened an OutputStream and sent the request to the webserver before trying to read the response.

String url = "http://learnsunjava.blogspot.com/";

conn = (HttpConnection)Connector.open(url,
Connector.READ_WRITE
);
if (conn.getResponseCode( ) == HttpConnection.HTTP_OK) {
is = conn.openInputStream( );
final int MAX_LENGTH = 128;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total <>) {
int count = is.read(buf, total, MAX_LENGTH - total);
if (count < 0) {
break;
}
total += count;
}
is.close( );
String reply = new String(buf, 0, total);
}

0 comments: