J2ME Networking:Connect Server PHP(HTTP GET)

Here is an example invoking PHP with GET parameters:

J2ME Source Code:

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

public class SimpleGETExample extends MIDlet {

private Display display;

String url = "http://127.0.0.1/midlet/testGET.php?type=2";

public SimpleGETExample() {
display = Display.getDisplay(this);
}

public void startApp() {
try {
testGET(url);
} catch (IOException e) {
System.out.println("IOException " + e);
e.printStackTrace();
}
}

public void pauseApp() { }
public void destroyApp(boolean unconditional) { }

void testGET(String url) throws IOException {
HttpConnection connection = null;
InputStream is = null;
OutputStream os = null;
StringBuffer stringBuffer = new StringBuffer();
TextBox textBox = null;

try {
connection = (HttpConnection)Connector.open(url);
connection.setRequestMethod(HttpConnection.GET);
connection.setRequestProperty("IF-Modified-Since","20 Jan 2001 16:19:14 GMT");
connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Confirguration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-CA");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
os = connection.openOutputStream();
is = connection.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
stringBuffer.append((char) ch);
}
textBox = new TextBox("Simple GET Test", stringBuffer.toString(), 1024, 0);
} finally {
if(is!= null) {
is.close();
}
if(os != null) {
os.close();
}
if(connection != null) {
connection.close();
}
}
display.setCurrent(textBox);
}
}

PHP Source Code:

$response = "Hello";

if (isset($_GET)) {
switch ($_GET["type"]) {
case 1: $response = "Good Morning"; break;
case 2: $response = "Good Afternoon"; break;
case 3: $response = "Good Evening"; break;
default: $response = "Hello"; break;
}
}
echo $response;
?>

5 comments:

  1. So usefull information.

    Thank you very much!

    ReplyDelete
  2. ขอบคุณครับ พอดีผมผมต้องทำโปรเจคเรื่อง j2me อยู่พอดีเลยครับกะว่าจะคิดติดต่อเวปแบบ get ไม่รู้จะเริ่มต้นยังไงดีพอมีตัวอย่างแบบสำเร็จพร้อม +php ไหมครับ

    ReplyDelete
  3. this is great.thanks for this post

    ReplyDelete
  4. i need the code for "Mobile Information Retrieval-clustering engine for mobile devices"

    ReplyDelete

 

Design by Blogger Buster | Distributed by Blogging Tips