Wednesday, February 21, 2007

Example Code:HttpConnection in J2ME #2

use SendDataViaHttp.java and HttpConnector.java together
/**
*
* @author sezera.blogspot.com
* @version 0010
*/
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class HttpConnector extends Thread{

private String url="http://localhost:8084/YourWebApp/YourServlet";
private String msg;
private SendDataViaHttp midlet;
/** Creates a new instance of HttpConnector */
public HttpConnector(SendDataViaHttp midlet,String msg) {
this.midlet =midlet;
this.msg = msg;
}
public synchronized void run(){
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;
try{
c = (HttpConnection)Connector.open(url);
// Set the request method and headers
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("User-Agent",
"Profile/MIDP-2.0 Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-US");
os = c.openOutputStream();
os.write(msg.getBytes());

is = c.openInputStream();

int contentLength = (int)c.getLength();
if (contentLength == -1) contentLength = 255;
byte[] raw = new byte[contentLength];
int length = is.read(raw);
String response = new String(raw,0,length);
midlet.get_response(response);
os.close();
is.close();
c.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}

No comments: