⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 oct01_ericg.txt

📁 TechTips j2me的常用技巧. 网络功能
💻 TXT
📖 第 1 页 / 共 2 页
字号:
/**
 * A MIDP application that fetches and displays an 
 * arbitrary image from the Web using the ImageAdapter 
 * servlet. This class depends on HttpConnectionHelper, 
 * described in an earlier J2ME Tech Tip.
 */

public class ImageClient extends MIDlet
                         implements CommandListener {

    // Adjust this URL appropriately for the adapter

    private static String adapterURL =
     "http://localhost:8080/servlet/ImageAdapter";

    // A default image to display...

    private static String defaultURL =
   "http://java.sun.com/products/images/duke_j2ee.gif";

    private Display display;
    private Command exitCommand = new Command( "Exit",
                                     Command.EXIT, 1 );
    private Command okCommand   = new Command( "OK", 
                                       Command.OK, 1 );
    private Command sendCommand = new Command( "Get",
                                       Command.OK, 1 );
    private TextBox entryForm;
    private int     screenHeight;
    private int     screenWidth;
    private int     numColors;

    public ImageClient(){
    }

    protected void destroyApp( boolean unconditional )
                    throws MIDletStateChangeException {
        exitMIDlet();
    }

    protected void pauseApp(){
    }

    protected void startApp()
                    throws MIDletStateChangeException {
        if( display == null ){ // first time called...
            initMIDlet();
        }
    }

    // First we display the dummy canvas so we can
    // get information about the display

    private void initMIDlet(){
        display = Display.getDisplay( this );
        entryForm = new EntryForm();
        display.setCurrent( new DummyCanvas() );
    }

    public void exitMIDlet(){
        notifyDestroyed();
    }

    public void commandAction( 
                            Command c, Displayable d ){
        if( c == sendCommand ){
            StatusForm f =
               new StatusForm( entryForm.getString() );
            display.setCurrent( f );
            f.start();
        } else if( c == okCommand ){
            display.setCurrent( entryForm );
        } else {
            exitMIDlet();
        }
    }

    // A dummy canvas to get the size of the screen

    class DummyCanvas extends Canvas {
        protected void paint( Graphics g ){
            screenHeight = getHeight();
            screenWidth  = getWidth();
            numColors    = display.numColors();

            // Go directly to the main screen

            display.setCurrent( entryForm );
        }
    }

    // The text entry form...

    class EntryForm extends TextBox {
        EntryForm(){
            super( "Enter a URL", defaultURL, 80, 0 );
            addCommand( exitCommand );
            addCommand( sendCommand );
            setCommandListener( ImageClient.this );
        }
    }

    // Show the image...

    class ShowImage extends Canvas {
        ShowImage( byte[] imageData ){
            image = Image.createImage( imageData, 0,
                                    imageData.length );
            display.setCurrent( this );
            addCommand( okCommand );
            setCommandListener( ImageClient.this );
        }

        protected void paint( Graphics g ){
            g.drawImage( image, 0, 0,
                         g.TOP | g.LEFT );
        }

        private Image image;
    }

    // A status for for displaying messages as the 
    // data is sent...

    class StatusForm extends Form
                 implements Runnable,
                        HttpConnectionHelper.Callback {
        StatusForm( String url ){
            super( "Status" );

            try {
                ByteArrayOutputStream bout =
                           new ByteArrayOutputStream();
                DataOutputStream      dout =
                          new DataOutputStream( bout );

                // Write info about the image and the
                // display settings for this device

                dout.writeUTF( "url" );
                dout.writeUTF( url );

                writeInt( 
                       dout, "minwidth", screenWidth );
                writeInt( 
                       dout, "maxwidth", screenWidth );
                writeInt( 
                     dout, "minheight", screenHeight );
                writeInt( 
                     dout, "maxheight", screenHeight );
                writeInt( 
                           dout, "colors", numColors );
                writeInt( dout, "reduce", 1 );
                writeInt( dout, "dither", 1 );

                dout.writeUTF( "" );

                data = bout.toByteArray();
                dout.close();
            }
            catch( IOException e ){
                // should handle this....
            }
        }

        void writeInt( DataOutputStream dout, 
                                String key, int value ) 
                                   throws IOException {
            dout.writeUTF( key );
            dout.writeUTF( Integer.toString( value ) );
        }

        // Updates the display.

        void display( String text ){
            if( message == null ){
                message = new StringItem( null, text );
                append( message );
            } else {
                message.setText( text );
            }
        }

        // We're done.

        void done( String msg ){
            display( msg != null ? msg : "Done." );
            addCommand( okCommand );
            setCommandListener( ImageClient.this );
        }

        // Callback for making the HTTP connection.

        public void prepareRequest( String originalURL,
                                  HttpConnection conn ) 
                                     throws IOException
        {
          conn.setRequestMethod( HttpConnection.POST );
            conn.setRequestProperty( "User-Agent",
           "Profile/MIDP-1.0 Configuration/CLDC-1.0" );
           conn.setRequestProperty( "Content-Language",
              "en-US" );
           conn.setRequestProperty( 
                               "Accept", "image/png" );
            conn.setRequestProperty( 
                               "Connection", "close" );
            conn.setRequestProperty( "Content-Length",
              Integer.toString( data.length ) );

            OutputStream os = conn.openOutputStream();
            os.write( data );
            os.close();
        }

        // Do the connection on a separate thread to 
        // keep the UI responsive...

        public void run(){
            HttpConnection conn = null;

            display( 
                "Obtaining HttpConnection object..." );

            try {
                conn =
                  HttpConnectionHelper.connect( 
                                           adapterURL,
                                               this );

                display( 
                      "Connecting to the server..." );
                int rc = conn.getResponseCode();

                if( rc == HttpConnection.HTTP_OK ){
                    try {
                        DataInputStream din = 
                                   new DataInputStream(
                              conn.openInputStream() );
             data = new byte[ (int) conn.getLength() ];
                        din.readFully( data );
                        din.close();
                    }
                    catch( IOException e ){
                    }

                    done( "Image received" );
                    new ShowImage( data );
                } else {
                    done( "Unexpected return code: " + 
                                                 rc );
                }

                conn.close();
            }
            catch( IOException e ){
                done( "Exception " + e +
                      " trying to connect." );
            }
        }

        // Starts the upload in the background...

        void start(){
            display( "Starting..." );

            Thread t = new Thread( this );
            try {
                t.start();
            }
            catch( Exception e ){
                done( "Exception " + e +
                      " trying to start thread." );
            }
        }

        private StringItem message;
        private byte[]     data;
    }
}

This MIDlet follows the same basic outline described in the 
August 20, 2001 J2ME Tech Tip, "Client-Server Communication over 
HTTP using MIDP and Servlets," but it changes a few things. For 
one, it sends different data: the body of the POST request 
consists of string pairs describing the URL to fetch and the 
display characteristics of the device. (By sending the data in 
the request body you avoid having to URL-encode it.) The data 
the MIDlet receives from the servlet is assumed to be the 
bytestream of an image in PNG format, which it collects and then 
displays using the javax.microedition.lcdui.Image class.

Notice how you can create an image directly from a byte array:

  Image img = Image.createImage( imageData, 0,
                                 imageData.length );

The image is displayed using a simple subclass of Canvas that 
does nothing but paint the image on the display.

To compile and run this MIDlet you'll also need the 
HttpConnectionHelper class that was shown in the December 18, 
2000 J2ME Tech Tip, "Making HTTP Connections with MIDP"
(http://java.sun.com/jdc/J2METechTips/2000/tt1218.html#tip2).

You can download the complete code for the client from 
http://www.ericgiguere.com/techtips/ImageClient.zip.
If you are using the J2ME Wireless Toolkit, you can simply unzip 
this file into the Toolkit's apps folder, and load and run the 
project directly using the KToolbar application.

.  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .  .

IMPORTANT: Please read our Terms of Use and Privacy policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/ 

* FEEDBACK
  Comments? Send your feedback on the J2ME Tech Tips to: 
  
  jdc-webmaster@sun.com

* SUBSCRIBE/UNSUBSCRIBE
  - To subscribe, go to the subscriptions page,
    (http://developer.java.sun.com/subscription/), choose
    the newsletters you want to subscribe to and click "Update".
  - To unsubscribe, go to the subscriptions page,
    (http://developer.java.sun.com/subscription/), uncheck the
    appropriate checkbox, and click "Update".
  - To use our one-click unsubscribe facility, see the link at 
    the end of this email:
    
- ARCHIVES
You'll find the J2ME Tech Tips archives at:

http://java.sun.com/jdc/J2METechTips/index.html


- COPYRIGHT
Copyright 2001 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA.

This document is protected by copyright. For more information, see:

http://java.sun.com/jdc/copyright.html

J2ME Tech Tips 
October 15, 2001

Sun, Sun Microsystems, Java, Java Developer Connection, J2ME, and
J2SE are trademarks or registered trademarks of Sun Microsystems, 
Inc. in the United States and other countries.




⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -