Sunday, December 9, 2007

Sending data to Servlet and getting the response

Servlets use HTTP request-reqponse protocol to send/recieve data from server. HTTPConnection interface of javax.microedition.io package is used.

Example below send any text to servlet and get response code from servlet.

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import java.io.*;
import java.util.Vector;

public class MidletServlet extends MIDlet implements CommandListener {
Display display = null;
Form form = null;
TextField tb = null;
String str = null;
String url = "http://localhost:8080/servlets-examples/servlet/getText";
Command backCommand = new Command("Back", Command.BACK, 0);
Command submitCommand = new Command("Submit", Command.OK, 2);
Command exitCommand = new Command("Exit", Command.STOP, 3);
private Test test;

public MidletServlet() {}

public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
form = new Form("Request Servlet");
tb = new TextField("Please input text: ","",30,TextField.ANY );
form.append(tb);
form.addCommand(submitCommand);
form.addCommand(exitCommand);
form.setCommandListener(this);
display.setCurrent(form);
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == backCommand) {
display.setCurrent(form);
} else if (c == submitCommand) {
str = tb.getString();
test = new Test(this);
test.start();
test.getServlet(str);
}
}


class Test implements Runnable {
MidletServlet midlet;
private Display display;
String text;

public Test(MidletServlet midlet) {
this.midlet = midlet;
display = Display.getDisplay(midlet);
}

public void start() {
Thread t = new Thread(this);
t.start();
}

public void run() {
StringBuffer sb = new StringBuffer();
try {
HttpConnection c = (HttpConnection) Connector.open(url);
c.setRequestProperty(
"User-Agent","Profile/MIDP-1.0, Configuration/CLDC-1.0");

c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);

DataOutputStream os =
(DataOutputStream)c.openDataOutputStream();

os.writeUTF(text.trim());
os.flush();
os.close();

// Get the response from the servlet page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
}
showAlert(sb.toString());
is.close();
c.close();
} catch (Exception e) {
showAlert(e.getMessage());
}
}
/* This method takes input from user like text and pass
to servlet */
public void getServlet(String text) {
this.text = text;
}

/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
};
}
import java.io.*;
import java.text.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class getText extends HttpServlet {

public void init() {
}

public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

DataInputStream in =
new DataInputStream((InputStream)request.getInputStream());

String text = in.readUTF();
String message;
try {
message = "100 ok";
} catch (Throwable t) {
message = "200 " + t.toString();
}
response.setContentType("text/plain");
response.setContentLength(message.length());
PrintWriter out = response.getWriter();
out.println(message);
in.close();
out.close();
out.flush();
}

public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

doPost(request,response);
}
}

No comments: