Http MIDlet : Networks « J2ME « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » J2ME » NetworksScreenshots 
Http MIDlet
Http MIDlet


/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X

*/


import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class HttpMIDlet extends MIDlet
                    implements CommandListener, Runnable {

    private Display display;
    private Form addressForm;
    private Form connectForm;
    private Form displayForm;
    private TextField serverURL;
    private StringItem messageLabel;
    private StringItem errorLabel;
    private Command okCommand;
    private Command exitCommand;
    private Command backCommand;

    protected void startApp() throws MIDletStateChangeException {
        if (display == null) {
            initialize();
            display.setCurrent(addressForm);
        }
    }

    protected void pauseApp() {
    }

    protected void destroyApp(boolean unconditional)
                        throws MIDletStateChangeException {
    }

    public void commandAction(Command cmd, Displayable d) {
        if (cmd == okCommand) {
            Thread t = new Thread(this);
            t.start();
            display.setCurrent(connectForm);
        else if (cmd == backCommand) {
            display.setCurrent(addressForm);
        else if (cmd == exitCommand) {
            try {
                destroyApp(true);
            catch (MIDletStateChangeException ex) {
            }
            notifyDestroyed();
        }
    }

    public void run() {
        InputStream is = null;
        HttpConnection conn = null;

        try {
            String url = serverURL.getString();
            if (!url.startsWith("http://"&& 
      !url.startsWith("https://")) {
                url = "http://" + url;
            }
            conn = (HttpConnection)Connector.open(url, Connector.READ_WRITE);
        catch (Exception ex) {
    System.out.println(ex);
    ex.printStackTrace();
            Alert alert = new Alert("Invalid Address",
                        "The supplied address is invalid\n" +
                        "Please correct it and try again.", null,
                        AlertType.ERROR);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert, addressForm);
            return;
        }

        try {
            // Fetch the required page, reading up
            // to a maximum of 128 bytes
            if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
                is = conn.openInputStream();
                final int MAX_LENGTH = 128;
                byte[] buf = new byte[MAX_LENGTH];
                int total = 0;
                while (total < MAX_LENGTH) {
                    int count = is.read(buf, total, MAX_LENGTH - total);
                    if (count < 0) {
                        break;
                    }
                    total += count;
                }
                is.close();
                String reply = new String(buf, 0, total);
                messageLabel.setText(reply);
            else {
                messageLabel.setText("Failed: error " + conn.getResponseCode() +
                                "\n" + conn.getResponseMessage());
            }
            
            // Get the response code and print all the headers
            System.out.println("Response code = " + conn.getResponseCode());
            System.out.println("Response message = " + conn.getResponseMessage());
            for (int i = 0; ; i++) {
                String key = conn.getHeaderFieldKey(i);
                String value = conn.getHeaderField(i);
                if (key == null) {
                    // Reached last header
                    break;
                }
                System.out.println(key + " = " + value);
            }
            conn.close();
            display.setCurrent(displayForm);
        catch (IOException ex) {
    System.out.println(ex);
    ex.printStackTrace();
            Alert alert = new Alert("I/O Error",
                        "An error occurred while communicating with the server.",
                        null, AlertType.ERROR);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert, addressForm);
            return;
        finally {
            // Close open streams
           try {
                if (is != null) {
                    is.close();
                    is = null;
                }
            catch (IOException ex1) {
            }
            try {
                if (conn != null) {
                    conn.close();
                    conn = null;
                }
            catch (IOException ex1) {
            }
        }
    }

    private void initialize() {
        display = Display.getDisplay(this);

        // Commands
        exitCommand = new Command("Exit", Command.EXIT, 0);
        okCommand = new Command("OK", Command.OK, 0);
        backCommand = new Command("Back", Command.BACK, 0);

        // The address form
        addressForm = new Form("HTTP Client");
        serverURL = new TextField("URL:"""256, TextField.ANY);
        addressForm.append(serverURL);
        addressForm.addCommand(okCommand);
        addressForm.addCommand(exitCommand);
        addressForm.setCommandListener(this);

        // The connect form
        connectForm = new Form("Connecting");
        messageLabel = new StringItem(null, "Connecting...\nPlease wait.");
        connectForm.append(messageLabel);
        connectForm.addCommand(backCommand);
        connectForm.setCommandListener(this);

        // The display form
        displayForm = new Form("Server Reply");
        messageLabel = new StringItem(null, null);
        displayForm.append(messageLabel);
        displayForm.addCommand(backCommand);
        displayForm.setCommandListener(this);
    }
}

           
       
Related examples in the same category
1. MIDlet to invoke a CGI script.
2. MIDlet to invoke a CGI script (POST method is used)
3. Https MIDlet
4. Pass a cookie (stored in rms) between the MIDlet and a Java servlet.
5. Use GET or POST to communicate with a Java servlet.
6. Use Java servlets sessions to tally golf scores.
7. Http Test
8. An example MIDlet to invoke a CGI script.An example MIDlet to invoke a CGI script.
9. Timer ServerTimer Server
10. Http ExampleHttp Example
11. Socket connectionSocket connection
12. Http ConnectionHttp Connection
13. Cookie MIDletCookie MIDlet
14. JargoneerJargoneer
15. Post MIDlet
16. Patchy MIDletPatchy MIDlet
17. MIDlet to invoke a CGI script (GET method).MIDlet to invoke a CGI script (GET method).
18. Fetch Page MidletFetch Page Midlet
19. Invoke Servlet Midlet 2
20. Invoke Servlet Midlet 1
21. MIDlet to invoke a CGI script (POST method is used) (2)MIDlet to invoke a CGI script (POST method is used) (2)
22. Demonstrates the functionality of DatagramConnection framework.Demonstrates the functionality of DatagramConnection framework.
23. Sample to demonstrate Http GET and POST from MIDlet
24. Get file from networkGet file from network
25. Midlet Servlet 2Midlet Servlet 2
26. MIDlet to fetch a page using an HttpConnectionMIDlet to fetch a page using an HttpConnection
27. A simple network clientA simple network client
28. Send client request and Get server responseSend client request and Get server response
29. Socket MIDletSocket MIDlet
30. www.amazon.com Book Ranking MIDletwww.amazon.com Book Ranking MIDlet
31. Time Server
32. DatagramSenderDatagramSender
33. Datagram Receiver
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.