Home of www.RoboHobby.com Java robotics project www.CubesAndCrosses.com
Train your logic skills in geometry
Create and delete one-color crosses
Play for free right in your browser!
Home-made CNC machine
Our new project -
How to make home-made CNC router
PICkit2 - Tutorials, Experiments
PICkit 2 - Small size USB programmer
from Microchip.
How to use it as a demo device for
USB programming in C language




www.RoboHobby.com
Home of www.RoboHobby.com
Java robotics project


Portable Notebook Table
How to make Portable Notebook Table.
Do it yourself!

Java SE SWING JSR-296 Example
How to run background task in
JSR-296 SWING application
with 'busy animation' in the status bar.
Useful addition to Netbeans template.

Java ME Code Examples
Java ME Source code examples
for robotics projects


Run Java ME Code Examples
How to run our Java ME code examples
for robotics projects



www.RoboHobby.com
/*
 * J2ME code example. Http Utils.
 * Part of www.RoboHobby.com Java robotics project.
 * www.RoboHobby.com
 */


package com.robohobby.me;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;

import javax.microedition.io.HttpConnection;

/**
 * @Ads.Taglet
 * @author Oleg

 */
public class HttpUtils  implements Runnable
{
    /**
     *
     */

    String url = "http://www.RoboHobby.com/time.jsp";

    HttpConnection httpConnection = null;
    InputStream inputStream = null;
    OutputStream outputStream = null;

    StringBuffer resultBuffer = new StringBuffer();

    CallBacks callBacks = CallBacks.getInstance();


    public void run()
    {

        //String url = "http://www.RoboHobby.com/time.jsp";

        String requetString = "";

        callBacks.robotMIDlet.getUrlInfoStringItem().setText(
        "url=" + url
                + "\r\n" ); //+" req="+requetString );
        callBacks.robotMIDlet.getInfoStringItem().setText( "started\r\n" );

        try
        {
            String targetUrl = this.url;
            getHttpData( targetUrl );
            String resultStr = resultBuffer.toString();
                    //sendData( url , requetString );
            callBacks.robotMIDlet.getResultStringItem().setText( resultStr );
            callBacks.robotMIDlet.getInfoStringItem().setText( "finished OK\r\n" );
        }
        catch ( IOException io_e )
        {
            callBacks.robotMIDlet.getInfoStringItem().setText( "Error io_e=" + io_e
                    + "\r\n");
        }
        catch ( Exception e )
        {
            callBacks.robotMIDlet.getInfoStringItem().setText( "Error e=" + e
                    + "\r\n");
        }

    }

    /**

     *
     * @throws java.io.IOException
     */
    void getHttpData( String targetUrl ) throws IOException
    {

        try {
            int responseCode = -1;

            boolean stop = false;

            // Opens the connection and checks redirections

            while ( !stop )
            {
                httpConnection = (HttpConnection)Connector.open( targetUrl ); //url);

                // Get Response Code of the connection
                responseCode = httpConnection.getResponseCode();

                if ( handleRedirectionResponseCode( responseCode ) )
                {
                    stop = true;
                }

            }

            if ( isErrorResponseCode( responseCode ) )
            {
                return;
            }

            // We handle only HTTP_OK (200) type response code.

            if ( responseCode != HttpConnection.HTTP_OK)
            {
                throw new IOException( "Error responseCode=" + responseCode );
            }

            // Get the HTTP ContentType
            String contentType = httpConnection.getType();
            handleContentType( contentType );

            //Open the InputStream, based on HttpConnection:

            inputStream = httpConnection.openInputStream();
            resultBuffer.setLength(0);

            //Value of the 'content-length' header field of
            //HTTP protocol. Might be -1 if it is unknown
            int contentLength = (int)httpConnection.getLength();


            //Even if the length is unknow, the response may have some data.

            //You can try to read them or you can stop here.
            //Or you can throw exception:
            /*
            if ( contentLength == -1 )
            {
                contentLength = 10;

                //throw new IOException( "Unknown 'content-length'!");
            }
            */

            if ( contentLength > 0 ) //We have some data

            {
                byte[] data = new byte[contentLength];

                int numberOfBytes = inputStream.read(data);

                //'numberOfBytes' should not be -1
                if ( numberOfBytes != -1 )
                {
                    hanldeByteArray(data);
                }

            }
            else

            {
                int ch;

                while ((ch = inputStream.read()) != -1)
                {
                    hanldeOneByte((byte)ch);
                }
            }
        } finally {
            if ( inputStream != null )
            {
                try

                {
                    inputStream.close();
                }
                catch ( IOException io_e )
                {
                    //Ignore this...
                }

            }

            try
            {
            if (httpConnection != null) {
                httpConnection.close();
             }
            }
            catch ( IOException io_e )
                {
                    //Ignore this...

                }

        }
    }

    private boolean isErrorResponseCode( int responseCode ) throws IOException
    {
        boolean result = false;

            if ( (responseCode == HttpConnection.HTTP_NOT_IMPLEMENTED)
            ||   (responseCode == HttpConnection.HTTP_VERSION)
            ||   (responseCode == HttpConnection.HTTP_INTERNAL_ERROR)
            ||   (responseCode == HttpConnection.HTTP_GATEWAY_TIMEOUT)
            ||   (responseCode == HttpConnection.HTTP_BAD_GATEWAY)
            )
            {

                if ( inputStream != null ) {
                     inputStream.close();
                }

                if ( outputStream != null) {
                    outputStream.close();
                }

                if (httpConnection != null) {
                    httpConnection.close();
                }

                result = true;
            }
        return result;
    }

    private boolean handleRedirectionResponseCode( int responseCode ) throws IOException
    {
        boolean result = false;

                if (( responseCode == HttpConnection.HTTP_TEMP_REDIRECT )
                ||  ( responseCode == HttpConnection.HTTP_MOVED_TEMP )
                ||  ( responseCode == HttpConnection.HTTP_MOVED_PERM) )
                {
                    // Get the new location

                    url = httpConnection.getHeaderField("location");

                    //Close the HTTP connection
                    httpConnection.close();

                    System.out.println("Do redirection to " + url);
                }
                else
                {
                    result = true;
                }
        return result;
    }

    /**

     * Process the Content Type.
     * @param contentType

     */
    void handleContentType(String contentType)
    {
        //Do some actions, based on ContentType:
        /*
        if ( !contentType.equals("MyType"))

        {
            throw new IOException( "Wrong ContentType!");
        }
        */
    }

    /**

     * Handles one character at a time.
     * @param b input byte

     */
    void hanldeOneByte(byte b) {
        resultBuffer.append((char)b);
    }

    /**
     * Handles array of data.

     * @param b an array of bytes.
     */

    void hanldeByteArray(byte[] b)
    {
        for (int i = 0; i < b.length; i++) {
            hanldeOneByte( b[i] );
        }
    }
    public String sendDataPages( String URL , byte[] bArray, int pageSize )
    {
        String retStr = "";
        //Split array:

        //int endPage = bArray.length/pageSize;
        int endPage = bArray.length/pageSize;

        for( int i = 0; i <= endPage; i++ )
        {
            try {
                String data = doEncode(bArray, i * pageSize, (i + 1) * pageSize);
                String params = "&p=" + i + "&e=" + endPage + "&s="
                + bArray.length + "&d=" + data + "&tmp=T";
                callBacks.robotMIDlet.getUrlInfoStringItem().setText("sendDataPages()
                params=" + "&p="
                + i + "&e="
                + endPage + "&s=" + bArray.length);

                String targetUrl = this.url;
                getHttpData( targetUrl + params );
                retStr = this.resultBuffer.toString();

            } catch (IOException io_e) {
                //ex.printStackTrace();

                retStr = ""+io_e;
            }
            //retStr = sendData( URL , params );
        }

        return retStr;
    }

  public String doEncode( byte[] bArray, int start, int end )
  {
      if ( bArray != null )
        {
                StringBuffer tmp = new StringBuffer();

                for ( int i = start ; i < end && i < bArray.length ; i++ )
                    {
                        tmp.append( ""+ bArray[i] + ";" );
                    }
                return tmp.toString();
        }
        return null;
  }

}









Google
 



Contact us:


My Skype name is oleg_skp
Start Skype text chatStart Skype text chat
View Skype profileView Skype profile
Start Skype voice callStart Skype voice call
Add me to your Skype contact listAdd to Skype contact list
Leave voicemail using SkypeLeave voicemail using Skype
Send a file using SkypeSend a file using Skype
Note: To use these links
the Skype program should
be installed on your computer.
You can load it for free from
their official site:
Contact via Skypewww.Skype.com
------------------