import javax.microedition.lcdui.*; import java.io.*; import javax.microedition.io.*; public class SendBesked extends TextBox implements CommandListener { private BeskedMidlet midletten; private Alert a; public SendBesked(BeskedMidlet midletten) { super("Skriv din besked", "", 50, TextField.ANY); this.midletten=midletten; setCommandListener(this); addCommand(new Command("Exit", Command.EXIT, 1)); addCommand(new Command("Send", Command.OK,1)); } public void commandAction(Command command, Displayable displayable) { if(command.getCommandType() == Command.EXIT) BeskedMidlet.quitApp(); else if(command.getCommandType() == Command.OK) try { sendData(getString(),"http://localhost:8080/modtag_besked.jsp"); } catch(IOException e){System.out.println(e);} } /** * Afsender en tekststreng til den angivne URL. * Efter afsendelsen af data kaldes metoden læsData(), som læser svaret fra * serveren. * @param data den tekst der skal sendes til serveren * @param URL URLén til den servlet eller JSP-side, der håndterer anmodningen */ private void sendData(String data, String URL)throws IOException { HttpConnection http = null; try { http = (HttpConnection) Connector.open(URL, Connector.READ_WRITE); http.setRequestMethod(HttpConnection.POST); DataOutputStream out = http.openDataOutputStream(); out.writeChars(data); out.flush(); læsData(http.openDataInputStream()); } catch (Exception ex) { System.out.println(ex); } finally { http.close(); //husk altid at lukke forbindelsen! } } /** * Læser en tekststreng fra den angivne InputStream. * Herefter vises en alert med indholdet af tekststrengen * @param is Indeholder de data, der kommer fra serveren */ private void læsData(InputStream is) throws IOException { StringBuffer besked = new StringBuffer(); try { int bogstav = is.read(); while ( bogstav != -1) { besked.append ((char) bogstav); bogstav = is.read(); } setString(""); a = new Alert("Besked afsendt!",besked.toString(),null,AlertType.INFO); a.setTimeout(5000); //Vis Alerten i 5 sek Display.getDisplay(midletten).setCurrent(a); } catch(Exception e) { System.out.println(e); } finally { if(is!=null) is.close(); } } }