Luís Tavares Luís Tavares - 1 month ago 11
HTTP Question

JavaME - HTTP Get - Send Values to Website

I'm building a project in which I want a method to make a simple http GET request in order to send two variables to an website via URL.
In a normal java project I would likely use java.net or apache and solve the issue in a matter of minutes. In JavaME, due to my lack of experience I'm not really being able to fulfill the task.

Basically what I want to do is having an url like

google.com/index.php?v1=x&v=y

being able to do a get request in order to send those variables via URL.

Any tips?

Thanks

Answer

Here's an example of how you could do something like that.

HttpConnection connection = null;
InputStream inputstream = null;
String url = null;
StringBuffer dataReceived = null;

    url = "http://www.google.com/index.php?v1=x&v=y";
    dataReceived = new StringBuffer();

    try {
        connection = (HttpConnection) Connector.open(url);
        connection.setRequestMethod(HttpConnection.GET);
        connection.setRequestProperty("Content-Type", "text/plain");
        connection.setRequestProperty("Connection", "close");

        if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
            inputstream = connection.openInputStream();
            int ch;
            while ((ch = inputstream.read()) != -1 ) {
                dataReceived.append((char) ch);

            }
        } else {
            // Connection not ok
        }
    } catch (Exception e) {
      // Something went wrong
    } finally {
        if (inputstream != null) {
            try {
                inputstream.close();
            } catch (Exception e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
            }
        }
    }

Note: I didn't test this specific code. I just edited some code I had lying around from a previous project of mine, so you may need to fix a few errors.