Java ME method to send a query string

Hi,
     have a java me method (code below) that when called should update a database on  a web server. The argument for the method is a  reference to a string object which typically contains http://blossompark.net/updates2.php?query= INSERT INTO coords VALUES ('','53.290797619999005 -6.27508931844',NOW())

The code compiles fine and the method is called by another class, but nothing seems to get to the web server database...
I would greatly appreciate some help with this as I have been trying to solve this for a long time and am going round in circles...
thanks
public void sendHttpUrl(String queryString){
     
     HttpConnection conn = null;
       
     try {
          conn = (HttpConnection) Connector.open(queryString);
          conn.setRequestMethod(HttpConnection.GET);
        conn.setRequestProperty("Content-Type","//text plain");
        conn.setRequestProperty("Connection", "close");

      //  int responseCode = conn.getResponseCode();
     }
           catch (IOException i){
            // message = "ERROR";
        }
finally 
      {
         try { if(conn != null)  conn.close(); } catch (IOException ioe) {}
        
      }

Open in new window

blossomparkAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

VenabiliCommented:
As a start, uncomment all that error handling and let's see if we can find out what the error is. I suspect that you do not manage to do the connection at all.
0
blossomparkAuthor Commented:
Hi Venabili,
changed the method syntax, see below.
Now getting an "unhanded exception error" when the app is run in a simulator and the method is called
  public String sendHttpUrl(String queryString){
     
     HttpConnection conn = null;
     String message = "";
    
     try {
          conn = (HttpConnection) Connector.open(queryString);
          conn.setRequestMethod(HttpConnection.GET);
        conn.setRequestProperty("Content-Type","//text plain");
        conn.setRequestProperty("Connection", "close");

       int responseCode = conn.getResponseCode();
     }
	   catch (IOException i){
             message = "ERROR";
	}
finally 
      {
         try { if(conn != null)  conn.close(); } catch (IOException ioe) {}
        
      }
     return message;

Open in new window

0
VenabiliCommented:
Change
catch (IOException i){
             message = "ERROR";
        }

to

catch (Exception i){
      message = "ERROR:" + i.getMessage();
}

to see what kind of exception you have.
0
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

blossomparkAuthor Commented:
I've installed the app with the above code to a mobile phone, when the method is called , there is no error displayed on the phone screen( maybe needs to be coded to display), also the database is still not updating...
0
blossomparkAuthor Commented:
ps the comment above does not relate to your most recent post
0
VenabiliCommented:
>maybe needs to be coded to display

Uhm... yes - this code just returns it back to whoever calls the method - you need the caller to then do something with the string.

And yes - it is obvious that it is not  updating - we try to find out why at the moment :)
0
blossomparkAuthor Commented:
when i choose the "Send Location by SMS "  option i am prompted with "Allow application to send text message to +353877525656?"
when i choose "Send location to website" option I do not get any prompt
0
VenabiliCommented:
That's because this is what you had written/done in the code invoking  the method above I suspect.

And sending messages and opening HTTP connections are different actions. So you cannot expect similar behaviour.

So what is the error string that you get now?
0
blossomparkAuthor Commented:
not getting any error string..just says "sending location to website  http://blossompark.net/updates2.php?query= INSERT INTO coords VALUES ('','53.290797619999005 -6.27508931844',NOW())"
0
VenabiliCommented:
Your method is returning a String to the place it gets invoked. Can you catch this string and print it somewhere so we can see what it says?

The fact that it is no more throwing an unhandled exception means that  the error is now handled but we still need to figure out what kind of exception it is.
0
blossomparkAuthor Commented:
ok..will try and catch
0
blossomparkAuthor Commented:
altered method (see code) to catch error..
the following is displayed when the method is called;

Your position:
ERROR: null
public String sendHttpUrl(String queryString){
     
     HttpConnection conn = null;
     String message = "";
    
     try {
          conn = (HttpConnection) Connector.open(queryString);
          conn.setRequestMethod(HttpConnection.GET);
        conn.setRequestProperty("Content-Type","//text plain");
        conn.setRequestProperty("Connection", "close");

       int responseCode = conn.getResponseCode();
     }
	   catch (Exception i){
             message = "ERROR: "+ i.getMessage();
             SendPosURL2.text.setText(message);
	}

Open in new window

0
VenabiliCommented:
replace
message = "ERROR: "+ i.getMessage();
with
message = "ERROR: "+ i.toString();

so we can see the type of the exception - the message is obviously not set.
0
blossomparkAuthor Commented:
displays:

ERROR: java.lang.IllegalArgumentException
0
VenabiliCommented:
OK - let's see where you have that illegal argument then. Hold on. Shouldn't
conn.setRequestProperty("Content-Type","//text plain");
    be
setRequestProperty("Content-Type","text/plain");
?

and why do you need
conn.setRequestProperty("Connection", "close");
?
0
blossomparkAuthor Commented:
copied those two statements from google site
0
VenabiliCommented:
Then change the first, remove the second and let's see how it works.

Do you remember from which site?

PS: http://java.sun.com/docs/books/j2mewireless/examples/src/examples/netclient/ConnectionManager.java has a really nice exception for connections from J2ME (it is for a post but the principle is similar)
0
blossomparkAuthor Commented:
changed first, commented out second...same error message...

commented out both, same  error..

dont remember which site...
0
blossomparkAuthor Commented:
Hi Venabili,
                   had a look at http://java.sun.com/docs/books/j2mewireless/examples/src/examples/netclient/ConnectionManager.java 
thanks for that,
am going to try and implement basic  HTTP GET method from the following article and build from there
http://developers.sun.com/mobility/midp/ttips/HTTPPost/

will keep you POSTED.... (very sad joke!!)
0
blossomparkAuthor Commented:
ok..been trying various flavours using HttpGET and am getting nowhere...
got  the code below from
http://wiki.forum.nokia.com/index.php/How_to_use_Http_POST_request_in_Java_ME

have installed and it works fine, returns the webpage  using  HTTP POST rather than GET.

Think I will try to use this as a template for my purpose,
I dont need to get anything  substantial returned from the web server, just need to update the database and that is why using a query string   with httpGET seemed the logical choice to me ...
however at this stage "the end justifies the means" Will keep you updated as to progress

package httpPost;

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



public class HttpPOST extends MIDlet implements CommandListener {

/** the default value for the url string is * * user can change it to some other urls within the application* */
private static String defaultURL = "http://blossompark.net/secondpage.php?q=53.290797619999005 -6.27508931844";

// GUI component for user to enter web url
private Display myDisplay = null;
private Form mainScreen;
private TextField requestField;

// GUI component for displaying header information
private Form resultScreen;
private StringItem resultField;

// the "send" button used on mainScreen
Command sendCommand = new Command("SEND", Command.OK, 1);
// the "back" button used on resultScreen
Command backCommand = new Command("BACK", Command.OK, 1);

public HttpPOST()
{
	// initializing the GUI components for entering web url
	myDisplay = Display.getDisplay(this);
	mainScreen = new Form("Type in a URL:");
	requestField = new TextField(null, defaultURL, 100, TextField.URL);
	mainScreen.append(requestField);
	mainScreen.addCommand(sendCommand);
	mainScreen.setCommandListener(this);
}

public void startApp() {myDisplay.setCurrent(mainScreen);}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable s)
{
	// when user clicks on "send" button on mainScreen
	if (c == sendCommand)
	{
		// retrieving the web url that user enteredString
		String urlstring = requestField.getString();

		// sending a POST request to web serverString
		String resultstring = sendPostRequest(urlstring);

		// displaying the page content retrieved from web server
		resultScreen = new Form("POST Result:");
		resultField = new StringItem(null, resultstring);
		resultScreen.append(resultField);
		resultScreen.addCommand(backCommand);
		resultScreen.setCommandListener(this);
		myDisplay.setCurrent(resultScreen);

	}
	else if (c == backCommand)
	{
		// do it all over again
		requestField.setString(defaultURL);
		myDisplay.setCurrent(mainScreen);
	}
}

// send a POST request to web server
public String sendPostRequest(String urlstring)
{
	HttpConnection hc = null;
	DataInputStream dis = null;
	DataOutputStream dos = null;

	String message = "";

	// specifying the query string
	String requeststring = "request=gettimestamp";
	try
	{
		// openning up http connection with the web server
		// for both read and write access
		hc = (HttpConnection) Connector.open(urlstring, Connector.READ_WRITE);

		// setting the request method to POST
		hc.setRequestMethod(HttpConnection.POST);

		// obtaining output stream for sending query string
		dos = hc.openDataOutputStream();
		byte[] request_body = requeststring.getBytes();

		// sending query string to web server
		for (int i = 0; i < request_body.length; i++)
		{
			dos.writeByte(request_body[i]);
		}
		// flush outdos.flush();

		// obtaining input stream for receiving HTTP response
		dis = new DataInputStream(hc.openInputStream());

		// reading the response from web server character by character
		int ch;
		while ((ch = dis.read()) != -1)
		{
			message = message + (char) ch;
		}

	}
	catch (IOException ioe)
	{
		message = "ERROR";
	}
	finally
	{
		// freeing up i/o streams and http connection
		try
		{
			if (hc != null)
				hc.close();
		}
		catch (IOException ignored)
		{
		}
		try
		{
			if (dis != null)
				dis.close();
		}
		catch (IOException ignored)
		{
		}
		try
		{
			if (dos != null)
				dos.close();
		}
		catch (IOException ignored)
		{
		}
	}
	return message;
}
}

Open in new window

0
blossomparkAuthor Commented:
have added the method below, when called  database not updated,however it is communicating with the website because it retrieves the html code of the webpage and displays it
public String sendHttpUrlPOST(String queryString){

     HttpConnection conn = null;
     DataInputStream dis = null;
     DataOutputStream dos = null;
     String url = "http://www.blossompark.net";
     String message = "";

     try {
         // openning up http connection with the web server
		// for both read and write access
          conn = (HttpConnection) Connector.open(url,Connector.READ_WRITE);

          // setting the request method to POST
          conn.setRequestMethod(HttpConnection.POST);
       
      // obtaining output stream for sending query string
		dos = conn.openDataOutputStream();
		byte[] request_body = queryString.getBytes();

                // sending query string to web server
		for (int i = 0; i < request_body.length; i++)
		{
			dos.writeByte(request_body[i]);
		}


                // obtaining input stream for receiving HTTP response
		dis = new DataInputStream(conn.openInputStream());

               // reading the response from web server character by character
		int ch;
		while ((ch = dis.read()) != -1)
		{
			message = message + (char) ch;
		}

          
    }
	catch (IOException ioe)
	{
	message = "ERROR: "+ ioe.toString();
             SendPosURL2.text.setText(message);
	}
	finally
	{
		// freeing up i/o streams and http connection
		try
		{
			if (conn != null)
				conn.close();
		}
		catch (IOException ignored)
		{
		}
		try 
		{
			if (dis != null)
				dis.close();
		}
		catch (IOException ignored)
		{
		}
		try
		{
			if (dos != null)
				dos.close();
		}
		catch (IOException ignored)
		{
		}
	}
	return message;
}
}

Open in new window

0
blossomparkAuthor Commented:
ok some progress i think!!!!
have introduced the encodeURL method from nokia website;
http://wiki.forum.nokia.com/index.php/How_to_encode_URL_in_Java_ME_%3F
when the sendHttpUrlGET method is called (code below) still getting error , but more meaningful (see attached image)...need to look at the encoding of the URL
public String sendHttpUrlGET(String queryString){

     HttpConnection conn = null;
     String url = "http://www.blossompark.net" + queryString;
     url =urlEncode(url);
     String message = "";

     try {
          conn = (HttpConnection) Connector.open(url,Connector.READ_WRITE);
          conn.setRequestMethod(HttpConnection.GET);
        conn.setRequestProperty("User-Agent",
        "Profile/MIDP-2.0 Confirguration/CLDC-1.1");
        //conn.setRequestProperty("Connection", "close");
       int responseCode = -1;
        responseCode = conn.getResponseCode();
      if (responseCode != -1){
       String responseMessage = "connection to server established";
       SendPosURL2.text.setText(responseMessage);
     }
     }
        catch (Exception i){
            // message = "ERROR: "+ i.getMessage();
             message = "ERROR: "+ i.toString();
             SendPosURL2.text.setText(message);
	}
finally
      {
         try { if(conn != null)  conn.close(); } catch (IOException ioe) {}

      }
     return message;
}

Open in new window

illegalArgument-Exception.jpg
0
VenabiliCommented:
:) yeah - the URI needs some work - you need to encode it.

PS: Please tell me that on the server side you do at least minimal check on who is sending you what and you do not just execute whatever SQL query is coming.
0
blossomparkAuthor Commented:
no checks,,,,just trying to get it working...at the testing stage....will introduce security at a later stage...

Regarding the  encoding, the URL has been encoded by  the urlEncode method so i'm not sure what else i can do there..any ideas?
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
blossomparkAuthor Commented:
Hi,
i posted the solution previously  but it is not showing up...
I found an encoder (see below) that i ran the query string through prior to opening a HTTP GET connection, the website database was then successfully updated... special thanks to venabili for his responses..
blossompark
private String EncodeURL(String URL)
	{
		URL = replace(URL, 'à', "%E0");
		URL = replace(URL, 'è', "%E8");
		URL = replace(URL, 'é', "%E9");
		URL = replace(URL, 'ì', "%EC");
		URL = replace(URL, 'ò', "%F2");
		URL = replace(URL, 'ù', "%F9");
		URL = replace(URL, '$', "%24");
		URL = replace(URL, '#', "%23");
		URL = replace(URL, '£', "%A3");
		URL = replace(URL, '@', "%40");
		URL = replace(URL, '\'', "%27");
		URL = replace(URL, ' ', "%20");

		return URL;
	}

	private String replace(String source, char oldChar, String dest)
	{
		String ret = "";
		for (int i = 0; i < source.length(); i++)
		{
			if (source.charAt(i) != oldChar)
				ret += source.charAt(i);
			else
				ret += dest;
		}
		return ret;
	}

}

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.