HTTP Connection Problem

Hi,

I cant open connection and i still dont know why.

Here the Main code

/* Mobile NFC Secured Payment Services

* Login.java

* Check RMS, Process Login

* Created on April 18, 2007, 8:19 AM

* Author: Chua Jie Sheng

*/

package main;

import function.Function;

import java.util.Timer;

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

import javax.microedition.rms.*;

import java.io.*;

import util.*;

import object.*;

import variable.*;

public class Main extends MIDlet implements CommandListener {

private Display display;

private Form loginForm;

private Alert splashScreen;

private Command loginCommand;

private Command exitCommand;

private RecordStore hpRMS;

//Item - Display after Checking

private StringItem title, instruction;

private TextField userId, hpNo;

private boolean newUser;

private Alert validateAlert;

private SMSConnection smsConnection;

private FormWait formWait;

private Alert loginAlert;

private Function f;

private Timer smsTimer;

private Thread smsReceive;

private SMSTimerTask smsTimerTask;

private MainMenu mainMenu;

private HTTPConnection httpConnection;

private Thread httpSend;

public Main() {

display = display.getDisplay(this);

loginForm = new Form("Login");

loginCommand = new Command("Login", Command.OK, 2);

exitCommand = new Command("Exit", Command.EXIT, 1);

openRMS();

if (hpRMS != null) {

if (checkRMS() > 0) {

existingUser(loginForm);

}

} else {

firstTimeUser(loginForm);

}

//HTTPConnection con = new HTTPConnection("http://localhost:8080/post.jsp");

//con.sendData("name=1");

//System.out.println(con.readData());

loginForm.addCommand(loginCommand);

loginForm.addCommand(exitCommand);

loginForm.setCommandListener(this);

validateAlert = new Alert("Error!");

validateAlert.setTimeout(Alert.FOREVER);

f = new Function();

formWait = new FormWait(this);

loginAlert = new Alert("");

loginAlert.setTimeout(Alert.FOREVER);

}

public void startApp() {

try {

splashScreen = new Alert("", "", Image.createImage("/images/sp.png"), AlertType.INFO);

splashScreen.setTimeout(3000);

display.setCurrent(splashScreen, loginForm);

} catch (Exception e) {

display.setCurrent(loginForm);

}

}

public void pauseApp() {

}

public void destroyApp(boolean unconditional) {

}

public void commandAction(Command command, Displayable displayable) {

if (command == exitCommand) {

exitMIDlet();

}

if (displayable == loginForm && command == loginCommand) {

boolean valid = false;

if (newUser == true) {

boolean validUserId = userId.getString().length() != 8;

boolean validHpNo = hpNo.getString().length() != 8;

if (validUserId == true && validHpNo == true) {

validateAlert.setString("Please enter 8 digits for UserId & HpNo.");

} else if (validUserId == true) {

validateAlert.setString("Please enter 8 digits for UserId.");

} else if (validHpNo == true) {

validateAlert.setString("Please enter 8 digits for HpNo.");

} else {

valid = true;

}

} else {

boolean validUserId = userId.getString().length() != 8;

if (validUserId == true) {

validateAlert.setString("Please enter 8 digits for UserId.");

} else {

valid = true;

}

}

if (valid == false) {

display.setCurrent(validateAlert, loginForm);

} else {

startHTTPThread();

stopHTTPThread();

startSMSThread();

display.setCurrent(formWait);

}

}

}

public void startSMSThread() {

if (smsConnection != null) {

smsConnection = null;

}

if (smsReceive != null) {

smsReceive = null;

}

smsConnection = new SMSConnection(this, Variable.SMS_PORT);

smsReceive = new Thread(smsConnection);

smsReceive.start();

smsTimer = new Timer();

smsTimerTask = new SMSTimerTask(this);

smsTimer.schedule(smsTimerTask, 40000);

}

public void stopSMSThread() {

smsConnection.disconnect();

smsConnection = null;

smsReceive = null;

smsTimer.cancel();

if (smsTimerTask != null)

smsTimerTask = null;

if (smsTimer != null)

smsTimer = null;

}

public void startHTTPThread() {

if (httpConnection != null) {

httpConnection = null;

}

if (httpSend != null) {

httpSend = null;

}

httpConnection = new HTTPConnection(ServletURL.M_LOGIN);

httpSend = new Thread(httpConnection);

httpSend.start();

httpConnection.openConnection();

httpConnection.sendData(userId.getString());

httpConnection.sendData(hpNo.getString());

httpConnection.sendData(""+newUser);

System.out.println(httpConnection.readData());

}

public void stopHTTPThread() {

httpConnection.disconnect();

httpConnection = null;

httpSend = null;

if (httpConnection != null) {

httpConnection = null;

}

if (httpSend != null) {

httpSend = null;

}

}

public void exitMIDlet() {

display.setCurrent(null);

destroyApp(true);

notifyDestroyed();

}

public Display getDisplay() {

return display;

}

public void openRMS() {

String[] recordStores = RecordStore.listRecordStores();

if (recordStores != null) {

for (int i = 0; i < recordStores.length; i++) {

if (recordStores.equals("hpDataRMS")) {

try {

hpRMS = RecordStore.openRecordStore("hpDataRMS", false);

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

}

public void closeRMS() {

try {

hpRMS.closeRecordStore();

} catch (Exception e) {

e.printStackTrace();

}

}

public void deleteRMS() {

try {

RecordStore.deleteRecordStore("hpDataRMS");

} catch (Exception e) {

e.printStackTrace();

}

}

public int checkRMS() {

int size = 0;

try {

size = hpRMS.getNumRecords();

} catch (Exception e) {

e.printStackTrace();

}

return size;

}

public String readRMS() {

String hpNo = "";

byte[] recData = new byte[50];

ByteArrayInputStream byteStream = new ByteArrayInputStream(recData);

DataInputStream dataStream = new DataInputStream(byteStream);

try {

hpRMS.getRecord(1, recData, 0);

hpNo = dataStream.readUTF();

} catch (Exception e) {

e.printStackTrace();

}

return hpNo;

}

public void writeRMS(String hpNo) {

ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

DataOutputStream dataStream = new DataOutputStream(byteStream);

try {

dataStream.writeUTF(hpNo);

dataStream.flush();

} catch (Exception e) {

e.printStackTrace();

}

byte[] recData = byteStream.toByteArray();

try {

if (checkRMS() == 0) {

hpRMS.addRecord(recData, 0, recData.length);

} else {

hpRMS.setRecord(1, recData, 0, recData.length);

}

} catch (Exception e) {

e.printStackTrace();

}

}

public void firstTimeUser(Form form) {

title = new StringItem("New User / New Phone", "");

instruction = new StringItem("", "Enter Your Preferred UserID and Your HP No.");

userId = new TextField("UserID:", "", 8, TextField.NUMERIC);

hpNo = new TextField("HP No.:", "", 8, TextField.NUMERIC);

newUser = true;

form.append(title);

form.append(instruction);

form.append(userId);

form.append(hpNo);

}

public void existingUser(Form form) {

title = new StringItem("Existing User", "");

instruction = new StringItem("", "Enter Your UserID to Logon to the Services.");

userId = new TextField("UserID:", "", 8, TextField.NUMERIC);

newUser = false;

form.append(title);

form.append(instruction);

form.append(userId);

}

public void smsProcessing(String text) {

String[] data = f.spilt(text, '!');

if (data[0].equals("success")) {

loginAlert.setTitle("Login Success!");

try {

loginAlert.setImage(Image.createImage("/images/connect.png"));

} catch (Exception e) {

;

}

if (data[1].equals("y")) {

loginAlert.setString("Login Successful!\nThere is bill for you to settle!");

} else {

loginAlert.setString("Login Successful!");

}

if (newUser == true) {

//writeRMS(hpNo.getString());

loginAlert.setString("Register Successful!\nPlease remember your UserID.");

}

mainMenu = new MainMenu(this);

} else {

try {

loginAlert.setImage(Image.createImage("/images/disconnect.png"));

} catch (Exception e) {

;

}

loginAlert.setTitle("Login Failed!");

loginAlert.setString("Please contact our helpdesk @ xxxxxxxx" + "\nError ID " + data[1]);

display.setCurrent(loginAlert, loginForm);

}

}

public Alert getLoginAlert() {

return loginAlert;

}

}

Ok..

Here the code doing the HTTP Connection

/* Mobile NFC Secured Payment Services

* httpConnection.java

* Create HTTP Connection and Send Data

* Created on April 18, 2007, 8:26 PM

* Author: Chua Jie Sheng

*/

package util;

import javax.microedition.io.*;

import java.io.*;

public class HTTPConnection implements Runnable {

private HttpConnection conn;

private OutputStream outStream;

private DataOutputStream dataOut;

private InputStream dataIn;

private String url;

public HTTPConnection(String url) {

this.url = url;

}

public void run() {

try {

conn = (HttpConnection)Connector.open(url);

conn.setRequestMethod(HttpConnection.POST);

conn.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");

conn.setRequestProperty("Content-type","application/x-www-form-urlencoded");

} catch (Exception e) {

e.printStackTrace();

}

}

public void openConnection() {

try {

dataOut = new DataOutputStream(conn.openOutputStream());

//dataIn = conn.openInputStream();

} catch (Exception e) {

e.printStackTrace();

}

}

public void sendData(String data) {

try {

dataOut.writeUTF(data);

dataOut.flush();

} catch (Exception e) {

e.printStackTrace();

}

}

public String readData() {

try {

dataIn = conn.openInputStream();

} catch (Exception e) {

e.printStackTrace();

}

String data = "";

String contentType = conn.getType();

int len = (int)conn.getLength();

byte[] dataBytes;

try {

if (len > 0) {

dataBytes = new byte[len];

int nb = dataIn.read(dataBytes, 0, len);

data = new String(dataBytes, 0, len);

} else {

dataBytes = new byte[2048];

int ch;

len = 0;

while((ch = dataIn.read()) != -1) {

dataBytes[len++] = (byte)ch;

}

data = new String(dataBytes, 0, len);

}

} catch (Exception e) {

e.printStackTrace();

}

return data;

}

public void disconnect() {

try {

if (dataIn != null) {

dataIn.close();

}

if (dataOut != null) {

dataOut.close();

}

if (conn != null) {

conn.close();

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

And lastly here the error

Starting emulator in execution mode

Running with storage root DefaultColorPhone

java.lang.NullPointerException

at util.HTTPConnection.openConnection(HTTPConnection.java:38)

at main.Main.startHTTPThread(Main.java:197)

at main.Main.commandAction(Main.java:143)

at javax.microedition.lcdui.Display$DisplayAccessor.commandAction(Display.java:1992)

at javax.microedition.lcdui.Display$DisplayManagerImpl.commandAction(Display.java:2822)

at com.sun.midp.lcdui.DefaultEventHandler.commandEvent(DefaultEventHandler.java:303)

at com.sun.midp.lcdui.AutomatedEventHandler.commandEvent(AutomatedEventHandler.java:670)

at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.run(DefaultEventHandler.java:658)

java.lang.NullPointerException

at util.HTTPConnection.sendData(HTTPConnection.java:47)

at main.Main.startHTTPThread(Main.java:199)

at main.Main.commandAction(Main.java:143)

at javax.microedition.lcdui.Display$DisplayAccessor.commandAction(Display.java:1992)

at javax.microedition.lcdui.Display$DisplayManagerImpl.commandAction(Display.java:2822)

at com.sun.midp.lcdui.DefaultEventHandler.commandEvent(DefaultEventHandler.java:303)

at com.sun.midp.lcdui.AutomatedEventHandler.commandEvent(AutomatedEventHandler.java:670)

at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.run(DefaultEventHandler.java:658)

java.lang.NullPointerException

at util.HTTPConnection.sendData(HTTPConnection.java:47)

at main.Main.startHTTPThread(Main.java:200)

at main.Main.commandAction(Main.java:143)

at javax.microedition.lcdui.Display$DisplayAccessor.commandAction(Display.java:1992)

at javax.microedition.lcdui.Display$DisplayManagerImpl.commandAction(Display.java:2822)

at com.sun.midp.lcdui.DefaultEventHandler.commandEvent(DefaultEventHandler.java:303)

at com.sun.midp.lcdui.AutomatedEventHandler.commandEvent(AutomatedEventHandler.java:670)

at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.run(DefaultEventHandler.java:658)

java.lang.NullPointerException

at util.HTTPConnection.sendData(HTTPConnection.java:47)

at main.Main.startHTTPThread(Main.java:201)

at main.Main.commandAction(Main.java:143)

at javax.microedition.lcdui.Display$DisplayAccessor.commandAction(Display.java:1992)

at javax.microedition.lcdui.Display$DisplayManagerImpl.commandAction(Display.java:2822)

at com.sun.midp.lcdui.DefaultEventHandler.commandEvent(DefaultEventHandler.java:303)

at com.sun.midp.lcdui.AutomatedEventHandler.commandEvent(AutomatedEventHandler.java:670)

at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.run(DefaultEventHandler.java:658)

java.lang.NullPointerException

at util.HTTPConnection.readData(HTTPConnection.java:57)

at main.Main.startHTTPThread(Main.java:202)

at main.Main.commandAction(Main.java:143)

at javax.microedition.lcdui.Display$DisplayAccessor.commandAction(Display.java:1992)

at javax.microedition.lcdui.Display$DisplayManagerImpl.commandAction(Display.java:2822)

at com.sun.midp.lcdui.DefaultEventHandler.commandEvent(DefaultEventHandler.java:303)

at com.sun.midp.lcdui.AutomatedEventHandler.commandEvent(AutomatedEventHandler.java:670)

at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.run(DefaultEventHandler.java:658)

java.lang.NullPointerException

at util.HTTPConnection.readData(HTTPConnection.java:63)

at main.Main.startHTTPThread(Main.java:202)

at main.Main.commandAction(Main.java:143)

at javax.microedition.lcdui.Display$DisplayAccessor.commandAction(Display.java:1992)

at javax.microedition.lcdui.Display$DisplayManagerImpl.commandAction(Display.java:2822)

at com.sun.midp.lcdui.DefaultEventHandler.commandEvent(DefaultEventHandler.java:303)

at com.sun.midp.lcdui.AutomatedEventHandler.commandEvent(AutomatedEventHandler.java:670)

at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.run(DefaultEventHandler.java:658)

[16136 byte] By [JieShenga] at [2007-11-27 2:01:08]
# 1

ya, your problem is a threading problem.

you're creating the httpconnection, and then on a second thread you're initializing it, while on the first thread you're trying to 'use' it immediately. The issue is that your second thread isn't finished setting up your HttpConnection object yet (in run()) by the time you try and use it by doing:

httpConnection.openConnection();

so, you have to do alllll of your httpConnection stuff on a second thread, not just part of it.

pandora_fooa at 2007-7-12 1:40:50 > top of Java-index,Java Mobility Forums,Java ME Technologies...
# 2
It works, Thanks
JieShenga at 2007-7-12 1:40:50 > top of Java-index,Java Mobility Forums,Java ME Technologies...
# 3

I'm not able to connect to any http: website.

After running the connection troubleshooting I could see that I can connect to any secure https: website. I've tried to restore from a previous date a couple of times, it allows me to connect just once and then I get the message, unable to connect. I'm running WINXP. Can someone tell me how I can correct this problem?

Thanks

vwwbba at 2007-7-12 1:40:50 > top of Java-index,Java Mobility Forums,Java ME Technologies...