Artigos
Java
Implementando uma rede em dispositivos móveis
Implementando uma rede em dispositivos móveis
O pacote javax.microedition.io inclui suporte a rede baseado em Generic Connection Framework para MIDP.
A ilustração abaixo usa o protocolo HTTP para ler dados de uma URL.
//Lê o cabeçalho e os dados do HTTP import java.io.*; import javax.microedition.midlet.*; import javax.microedition.io.*; import javax.microedition.lcdui.*;
public class httpMIDLET extends MIDlet { private Display display; private String url = "http://server/hello.txt"; public httpMIDLET() { display = Display.getDisplay(this); }
public void startApp() { getData(url); }
private void getData(String url) throws IOException { StringBuffer b = new StringBuffer(); InputStream is = null; HttpConnection c = null; TextBox t = null; try { long len = 0 ; int ch = 0; c = (HttpConnection)Connector.open(url); is = c.openInputStream(); len =c.getLength(); if( len != -1) { // Lê exatamente o Content-Length bytes for(int i =0 ; i < len ; i++ ) { if((ch = is.read()) != -1) { b.append((char) ch); } } } else { //Lê até que a conexão é fechada. while ((ch = is.read()) != -1) { len = is.available() ; b.append((char)ch); } } t = new TextBox("Http Data",b.toString(), 1024, 0); } finally { is.close(); c.close(); } display.setCurrent(t); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } }
Abaixo do método post um pedido com alguns cabeçalhos e índices para o servidor.
public void postHttpdata(Sring url) throws IOException { HttpConnection c = null; OutputStream os = null;
try { c = (HttpConnection)Connector.open(url);
// Configura o método de pedido e os cabeçalhos c.setRequestMethod(HttpConnection.POST); c.setRequestProperty( "If-Modified-Since","7 Sep 2005 19:43:31 GMT"); c.setRequestProperty( "User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
c.setRequestProperty( "Content-Language", "en-US");
// Obtendo a saída os = c.openOutputStream(); os.write("How are you\n" + c.getBytes()); os.flush();
} finally { os.close(); c.close(); } } |