Wednesday, August 6, 2008

Use GET Method to communicate with a HTTP Server from J2ME application

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

public class HttpGetTest extends MIDlet {
private Display display;

public HttpGetTest() {
try {
getBirthdayFromNameUsingGet();
}
catch (IOException e) {
System.out.println("IOException " + e.toString());
}
}
public void startApp() {
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}

public void getBirthdayFromNameUsingGet() throws IOException {

HttpConnection httpConn = null;
String url = "http://127.0.0.1/dbtest.php?user_name=sadat&password=sadat&prov_code=A";
//String url="http://www.google.com.bd/";

InputStream is = null;
OutputStream os = null;

try {
// Open an HTTP Connection object
httpConn = (HttpConnection)Connector.open(url);

// Setup HTTP Request
httpConn.setRequestMethod(HttpConnection.GET);
httpConn.setRequestProperty("User-Agent","Profile/MIDP-1.0 Confirguration/CLDC-1.0");

/** Initiate connection and check for the response code. If the
response code is HTTP_OK then get the content from the target
**/
int respCode = httpConn.getResponseCode();
if (respCode == httpConn.HTTP_OK) {
StringBuffer sb = new StringBuffer();
os = httpConn.openOutputStream();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1)
sb.append((char) chr);
// Web Server just returns the birthday in mm/dd/yy format.
System.out.println( sb.toString());
}
else {
System.out.println("Error in opening HTTP Connection. Error#" + respCode);
}

} finally {
if(is!= null)
is.close();
if(os != null)
os.close();
if(httpConn != null)
httpConn.close();
}
}
}

No comments:

search engine

Custom Search