Wednesday, August 6, 2008

Use of POST Method to HTTP Server in J2ME application

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

public class HttpPostTest extends MIDlet implements CommandListener,Runnable {
private Display display;
private Form form;
private Command exitCommand;
private Command postCommand;
private TextField text1;

public void startApp() {
display = Display.getDisplay(this);
form = new Form("");
text1 = new TextField("Name:", "", 50, TextField.ANY);
form.append(text1);
exitCommand = new Command("Exit", Command.EXIT, 0);
postCommand = new Command("Post", Command.SCREEN, 0);
form.addCommand(exitCommand);
form.addCommand(postCommand);
form.setCommandListener(this);
display.setCurrent(form);
}

protected void pauseApp() {
}

protected void destroyApp(boolean arg0) {
}

public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == postCommand) {
Thread t=new Thread(this);
t.start();
}
}

public void run(){
try{
httpPost();
}catch(IOException e){
showAlert(e.getMessage());
}
}

private void showAlert(String s) {
Alert a = new Alert("Exception", s, null, null);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a, form);
}

public void httpPost() throws IOException {
HttpConnection http = null;
OutputStream oStrm = null;
InputStream iStrm = null;
String url = "http://127.0.0.1:4040/posttest.php";
try {
http = (HttpConnection) Connector.open(url);
oStrm = http.openOutputStream();
System.out.println("outputstream opened");
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// If you experience connection/IO problems, try
// removing the comment from the following line
// http.setRequestProperty("Connection", "close");

byte data[] = ("name=" + text1.getString()).getBytes();
oStrm.write(data);
System.out.println("written");
//iStrm = http.openInputStream();
System.out.println("input stream opened");
int respCode = http.getResponseCode();
if (respCode == http.HTTP_OK) {
StringBuffer sb = new StringBuffer();
iStrm = http.openDataInputStream();
int chr;
while ((chr = iStrm.read()) != -1)
sb.append((char) chr);
System.out.println(sb.toString());
showAlert(sb.toString());
}
} finally {
if (iStrm != null)
iStrm.close();
if (oStrm != null)
oStrm.close();
if (http != null)
http.close();
}
}
}

PHP CODE:
< ? PHP
$name=$_POST['name'];
print "Wellcome ".$name;
?>

No comments:

search engine

Custom Search