Code: Koneksi Client HTTP pada Java ME (J2ME)

This code is presented by JENI (Java Education Network Indonesia)

/*******************************************
* Percobaan 1 : Mencoba Koneksi HTTP *
* Tested On : Motorola C380 *
* Test Result : Work Properly *
*******************************************/
import javax.microedition.io.*;
import java.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class HttpExample extends MIDlet implements CommandListener {

 Display display;
 Form formHttp;
 Command exitCommand = new Command("Exit", Command.EXIT, 0);
 HttpConnection connection = null;
 InputStream iStream = null;
 byte[] data = null;

 public HttpExample() {
 formHttp = new Form("HTTP Example");
 formHttp.addCommand(exitCommand);
 formHttp.setCommandListener(this);
 try {
 connection = (HttpConnection) Connector.open("http://gammablue.com/bulkimport/hello-world-import.txt");
 int code = connection.getResponseCode();
 switch (code) {
 case HttpConnection.HTTP_OK:
 iStream = connection.openInputStream();
 int length = (int) connection.getLength();
 if (length > 0) {
 data = new byte[length];
 int totalBytes = 0;
 int bytesRead = 0;
 while ((totalBytes < length)) {
 bytesRead = iStream.read(
 data, totalBytes, length - totalBytes);
 if (bytesRead > 0) {
 totalBytes += bytesRead;
 } else {
 break;
 }
 }
 formHttp.append(new String(data));
 } else {
//panjang tidak diketahui, baca tiap karakter
 }
 break;
 default:
 break;
 }
 } catch (Exception e) {
 }
 }

 public void startApp() {
 if (display == null) {
 display = Display.getDisplay(this);
 display.setCurrent(formHttp);
 }
 }

 public void pauseApp() {
 }

 public void destroyApp(boolean d) {
 }

 public void commandAction(Command c, Displayable d) {
 if (c == exitCommand) {
 destroyApp(true);
 notifyDestroyed(); // Exit
 }
 }
}

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: