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 web server before trying to read the response.

 String url = "http://www.java-tips.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 < MAX_LENGTH) {
    int count = is.read(buf, total, MAX_LENGTH - total);
    if (count < 0) {
      break;
    }
    total += count;
  }
  is.close( );
  String reply = new String(buf, 0, total);
}

 

 

 

 Related Tips