Kết nối HTTP

Một phần của tài liệu Luận văn:" Lập trình thiết bị do động trên J2ME" docx (Trang 96 - 101)

HTTP là giao thức duy nhất chắc chắn được hỗ trợ bởi MIDP 1.0. Chúng ta có thể

giao tiếp với máy chủ hay bất kỳ thiết bị từ xa nào có hỗ trợ giao thức này nhờ vào lớp HttpConnection. Lớp Connector cung cấp cho người dùng bảy phương thức để

tạo kết nối tới máy chủ. Ba phương thức trong số đó là các biến thể của phương thức open(). Các phương thức này được mô tả trong bảng sau:

Các phương thức của lớp javax.microedition.io.Connector

Phương thức Mô tả

static Connection open(String name)

Tạo một kết nối có chếđộ

READ_WRITE static Connection open(String name,

int mode)

Tạo một kết nối với chế độ được chỉđịnh

static Connection open(String name, int mode, boolean timeouts)

Tạo một kết nối với chế độ được chỉđịnh, thêm ngoại lệ

time out static InputStream openInputStream(String name) Tạo kết nối luồng nhập static OutputStream openOutputStream(String name) Tạo kết nối luồng xuất static DataInputStream openDataInputStream(String name) Tạo kết nối luồng nhập kiểu DataInputStream static DataOutputStream openDataOutputStream(String name) Tạo kết nối luồng xuất kiểu DataOutputStream

Dưới đây là đoạn code mở kết nối thông qua stream // Create a ContentConnection

String url = “http://www.corej2me.com”;

ContentConnection connection = (ContentConnection) Connector.open(url); // With the connection, open a stream

InputStream iStrm = connection.openInputStream(); // ContentConnection includes a length method int length = (int) connection.getLength();

if (length != -1) {

byte imageData[] = new byte[length]; // Read the data into an array

iStrm.read(imageData); }

Thật ra chúng ta có thể tọa một kết nối InputStream mà không cần sự có mặt của ContentConnection. Tuy nhiên, phương pháp này có hạn chế là không cung cấp phương thức để xác định chiều dài dữ liệu

Dưới đây là cách mở một kết nối dạng HttpConnection:

String url = “http://www.corej2me.com/midbook_v1e1/ch14/duke.png”; HttpConnection http = (HttpConnection) Connector.open(url);

Sau khi được mở, kết nối này cung cấp truy xuất đến rất nhiều loại luồng mà InputStream và DataInputStream là hai trong số đó. Tuy nhiên thế mạnh thực sự

của kết nối HttpConnection lại nằm ở chỗ nó có khả năng giúp cho lập trình viên loại bỏ các gánh nặng của các câu lệnh HTTP.

Dưới đây là ví dụ đơn giản, đầu tiên MIDlet sẽ download và hiển thị hình ảnh đã tải về. MIDlet sẽ dử dụng ByteArrayOutputStream để chứa dữ liệu tải về bởi vì ta không dùng ContentConnection nên không thể biết kích cỡ dữ liệu tải về

/*--- * DownloadImage.java * */ import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; import java.io.*;

public class DownloadImage extends MIDlet implements CommandListener { private Display display;

private TextBox tbMain; private Form fmViewPng; private Command cmExit; private Command cmView; private Command cmBack; public DownloadImage() {

display = Display.getDisplay(this);

// Create the textbox, allow maximum of 50 characters (adsbygoogle = window.adsbygoogle || []).push({});

tbMain = new TextBox("Enter url", "http://localhost/intel.png", 55, 0); // Create commands and add to textbox

cmExit = new Command("Exit", Command.EXIT, 1); cmView = new Command("View", Command.SCREEN, 2); tbMain.addCommand(cmExit);

tbMain.addCommand(cmView ); // Set up a listener for textbox tbMain.setCommandListener(this);

// Create the form that will hold the image fmViewPng = new Form("");

// Create commands and add to form

cmBack = new Command("Back", Command.BACK, 1); fmViewPng.addCommand(cmBack);

// Set up a listener for form

fmViewPng.setCommandListener(this); }

public void startApp() {

display.setCurrent(tbMain); }

public void pauseApp() { }

public void destroyApp(boolean unconditional) { }

// If the Command button pressed was "Exit" if (c == cmExit) { destroyApp(false); notifyDestroyed(); } else if (c == cmView) {

// Download image and place on the form try {

Image im;

if ((im = getImage(tbMain.getString())) != null) { ImageItem ii = new ImageItem(null, im,

ImageItem.LAYOUT_DEFAULT, null); // If there is already an image, set (replace) it if (fmViewPng.size() != 0) fmViewPng.set(0, ii); else // Append the image to the empty form

fmViewPng.append(ii); }

else fmViewPng.append("Unsuccessful download."); // Display the form with image

display.setCurrent(fmViewPng); } catch (Exception e) { System.err.println("Msg: " + e.toString()); } } else if (c == cmBack) { display.setCurrent(tbMain); } }

private Image getImage(String url) throws IOException {

InputStream iStrm = (InputStream) Connector.openInputStream(url); Image im = null;

try {

ByteArrayOutputStream bStrm = new ByteArrayOutputStream(); int ch;

while ((ch = iStrm.read()) != -1) bStrm.write(ch); // Place into image array

byte imageData[] = bStrm.toByteArray(); // Create the image from the byte array

im = Image.createImage(imageData, 0, imageData.length); }

finally {

// Clean up if (iStrm != null) iStrm.close(); }

return (im == null ? null : im); } (adsbygoogle = window.adsbygoogle || []).push({});

}

Một textbox sẽ cho phép nhập địa chỉ URL

Một phần của tài liệu Luận văn:" Lập trình thiết bị do động trên J2ME" docx (Trang 96 - 101)