J2ME Networking - PowerPoint PPT Presentation

1 / 40
About This Presentation
Title:

J2ME Networking

Description:

For example, the following request sends two parameters: pOne='one bit' and pTwo='two' http://localhost/midp/simple?pOne=one bit&pTwo=two. 21. J2ME Networking ... – PowerPoint PPT presentation

Number of Views:268
Avg rating:3.0/5.0
Slides: 41
Provided by: sta1
Category:
Tags: j2me | networking | pone

less

Transcript and Presenter's Notes

Title: J2ME Networking


1
J2ME Networking
2
Introduction
  • J2ME provides networking features to the mobile
    devices.
  • It is possible to get up-to-the-minute stock
    quotes or updated currency exchange rates on a
    mobile phone.
  • The javax.microedition.io classes and interfaces
    handle the networking capability of MIDP.
  • The java.io package provides input/output (I/O)
    capability to MIDP.

3
J2ME Networking Categories
  • J2ME networking has 3 categories
  • Low-level IP networking
  • HTTP networking
  • Secure networking
  • The most critical aspect of J2ME network
    connectivity is communication between a mobile
    device and Web server.

4
Low-level IP networking
  • This category involves socket, datagram, serial
    port, and file I/O communication.
  • Socket-based communication conforms to the
    connection-oriented TCP/IP protocol.
  • Datagram-based communication conforms to the
    connectionless UDP/IP protocol.
  • e.g. URI for a datagram connection for sending to
    a server on a certain port
  • datagram//123.456.789.121234
  • Low-level IP networking can also handle file I/O
    and can allow a MIDlet to use a local serial port.

5
HTTP networking
  • The communication between a mobile device and a
    Web server is based on HTTP (Hypertext Transfer
    Protocol).
  • HTTP is a connection-oriented request-response
    protocol.

6
Secure networking
  • Secure Networking in J2ME involves additional
    interfaces available for secure communication
    with Web-based network services.
  • Secure interfaces are provided by HTTPS and
    SSL/TLS protocol access over the IP network.

7
The Connection Framework
  • J2ME networking was designed to address the
    diverse needs of a wide range of mobile devices.
  • At the same time, the networking system must be
    device specific.
  • To meet these challenges, it introduces the
    concept of a generic connection framework.
  • Generic connection framework is to define the
    general aspects of the networking and file I/O in
    the form of Java interfaces for a broad range of
    handheld devices
  • Leave the actual implementations of these
    interfaces to individual device manufacturers.

8
The Connection Framework
9
URL Handling in J2ME
  • URL handling in J2ME involves opening a
    connection to the Web server from the mobile
    device and handling data I/O between the two.
  • The process happens in the following stages
  • Setup
  • Connected
  • Closed
  • J2ME defines the javax.microedition.io.Connector
    class to create all the connection objects.
  • In URL handling, Connector.open() is used to open
    a URL it returns an HttpConnection object.

10
URL Handling in J2ME
  • The string parameter to the Connector.open()
    method is a valid URL.
  • The URL string varies depending on the
    communication protocol, as Examples 1 through 5
    below demonstrate.
  • Example 1. Invoking HTTP-based
    communicationConnection conn Connector.open("h
    ttp//www.yahoo.com") Example 2. Invoking
    stream-based socket communicationConnection conn
    Connector.open("socket//localhost9000")

11
URL Handling in J2ME
  • Example 3. Invoking datagram-based socket
    communicationConnection conn
    Connector.open("datagram//9000") Example
    4. Invoking serial port communicationConnection
    conn Connector.open("comm0baudrate9000")
    Example 5. Invoking file I/O communicationConne
    ction conn Connector.open("file//myfile.dat")

12
URL Handling in J2ME
  • The Connector.open() method also accepts the
    access mode (values READ, WRITE, and READ_WRITE),
    and a flag to indicate that the caller wants a
    timeout notification.
  • static Connection open(String name, int mode)
  • static Connection open(String name, int mode,
    boolean timeouts)
  • The method openInputStream() of Connector opens
    an input stream of bytes (java.io.InputStream).

13
URL Handling in J2ME
  • Similarly, a java.io.OutputStream representing an
    output stream of bytes.
  • The counterparts of InputStream and OutputStream
    are java.io.DataInputStream and
    java.io.DataOutputStream, respectively.
  • A DataInputStream/DataOutputStream lets an
    application read/write primitive Java data types.

14
Example - Fetch a Page
  • Use a HttpConnection to fetch a web page and
    display the content using a TextBox.

Source of ict web page http//www.vtc.edu.hk/ive/
ty/ict/
15
Example - Fetch a Page
  • import java.io.
  • import javax.microedition.io.
  • import javax.microedition.lcdui.
  • import javax.microedition.midlet.
  • public class NetworkFetchAPage extends MIDlet
  • private Display display
  • String url "http//www.vtc.edu.hk/ive/ty/ict
    /"
  • public NetworkFetchAPage()
  • display Display.getDisplay(this)
  • public void startApp()
  • HttpConnection c null
  • InputStream s null
  • StringBuffer b new StringBuffer()
  • TextBox t null

16
Example - Fetch a Page
  • try
  • c (HttpConnection)
    Connector.open(url)
  • s c.openInputStream()
  • int ch
  • while((ch s.read()) ! -1)
  • b.append((char) ch)
  • System.out.println(b.toString())
  • t new TextBox("ICT",
  • b.toString(), 1024, 0)
  • catch (IOException e)
  • System.out.println("IOException "
    e)
  • e.printStackTrace()

17
Example - Fetch a Page
  • try
  • if(s ! null)
  • s.close()
  • if(c ! null)
  • c.close()
  • catch (IOException e)
  • System.out.println("IOException "
    e)
  • e.printStackTrace()
  • // display the contents of the file in a
    text box.
  • display.setCurrent(t)
  • public void pauseApp()
  • public void destroyApp(boolean unconditional)

18
Passing Parameters to Server
  • Typically, an HTTP request to a server is
    accompanied by information needed by the server
    to process the request.

19
Passing Parameters to Server
  • e.g. Login in case.
  • A server must authenticate a client using the
    clients user ID and password.
  • The client sends the user ID and password along
    with the HTTP request.
  • Two techniques are used to send data to the
    server GET or POST request methods.
  • The GET request method requires that data be
    concatenated to the URL of the server.
  • The POST request method requires that each pair
    value be written to the output stream.

20
Passing Parameters to Server
  • Data sent to a server must be in a pair value
    set
  • field name
  • the value associated with the field.
  • The field name and value must be separated by an
    equal sign ().
  • The pair value sets are separated from the URL by
    a question mark (?).
  • Each pair value set is separated from other pair
    value sets by an ampersand ().
  • The space character is converted to a plus ()
    sign.
  • For example, the following request sends two
    parameters pOne"one bit" and pTwo"two"http//
    localhost/midp/simple?pOneonebitpTwotwo

21
Example Login - Get Method
  • User enters a login id and a password
  • The MIDlet sends the request to the web server
  • The web server executes a simple php script and
    validates the user according to the following
    table
  • Login ID Password
  • andy cat
  • paul panda
  • jacky doctor
  • peter a1 b

22
Example - Successful Login
  • If password is correct, display the menu screen

23
Example - Login Fails
  • If login fails, display an Alert screen to tell
    the user to try again.
  • NoteThe network connection should be done in a
    separated thread other than the CommandAction
    thread.

24
Example - Login
  • import java.io.
  • import javax.microedition.io.
  • import javax.microedition.lcdui.
  • import javax.microedition.midlet.
  • public class NetworkLoginDemo extends MIDlet
  • implements CommandListener, Runnable
  • private Display display
  • private TextField userName
  • private TextField password
  • private Form form
  • private Command cancel
  • private Command login
  • public NetworkLoginDemo()
  • display Display.getDisplay(this)
  • userName new TextField("LoginID", "",
    10, TextField.ANY)
  • password new TextField("Password", "",
    10,
  • TextField.PASSWORD)

25
Example - Login
  • form new Form("Sign in")
  • cancel new Command("Cancel", Command.CANCEL,
    2)
  • login new Command("Login", Command.OK, 2)
  • public void startApp()
  • HttpConnection c null
  • InputStream s null
  • display Display.getDisplay(this)
  • form.append(userName)
  • form.append(password)
  • form.addCommand(cancel)
  • form.addCommand(login)
  • form.setCommandListener(this)
  • display.setCurrent(form)

26
Example - Login
  • public void validateUser()
  • // Do network loading in a separate
    thread.
  • Thread t new Thread(this)
  • t.start()
  • public void run()
  • String name userName.getString()
  • String pwd password.getString()
  • StringBuffer b new StringBuffer("")
  • HttpConnection hc null
  • InputStream in null
  • String parameter
  • String result
  • String url
  • "http//ictlab.tyict.vtc.edu.hk/nelsonc
    /mobile/login_demo.php?"

27
Example - Login
  • parameter "name" name
  • parameter "password" pwd.replace('
    ', '')
  • System.out.println(urlparameter)
  • try
  • hc (HttpConnection)Connector.open(ur
    lparameter)
  • in hc.openInputStream()
  • int ch
  • while((ch in.read()) ! -1)
  • b.append((char) ch)
  • catch (IOException e)
  • e.printStackTrace()

Hint To debug your program, copy and paste the
link (e.g. http//ictlab.tyict.vtc.edu.hk/nelsonc
/mobile/login_demo.php?nameandypasswordcat) to
the browser and check the connection and result
returned.
28
Example - Login
  • try
  • if(in ! null)
  • in.close()
  • if(hc ! null)
  • hc.close()
  • catch (IOException e)
  • e.printStackTrace()
  • result b.toString().trim()
  • if (result.equals("OK"))
  • menu()
  • else
  • tryAgain()

The sever side php script lt?php name_GET'name
' pwd_GET'password' if (name"andy"
pwd"cat") echo "OK" else if (name"paul"
pwd"panda") echo "OK" else if
(name"jacky" pwd"doctor") echo
"OK" else if (name"peter" pwd"a1 b")
echo "OK" else echo "invalid" ?gt
29
Example - Login
  • public void menu()
  • List services new List("Choose one",
    Choice.EXCLUSIVE)
  • services.append("Check Mail", null)
  • services.append("Compose", null)
  • services.append("Addresses", null)
  • services.append("Options", null)
  • services.append("Sign Out", null)
  • display.setCurrent(services)
  • public void tryAgain()
  • Alert error new Alert("Login
    Incorrect", "Please try again",
  • null,
    AlertType.ERROR)
  • error.setTimeout(Alert.FOREVER)
  • password.setString("")
  • display.setCurrent(error, form)

30
Example - Login
  • public void commandAction(Command c,
    Displayable d)
  • String label c.getLabel()
  • if(label.equals("Cancel"))
  • notifyDestroyed()
  • else if(label.equals("Login"))
  • validateUser()
  • public void pauseApp()
  • public void destroyApp(boolean unconditional)

31
Post Method
  • Posting a form is a little more complicated on
    the MIDlet side.
  • A few request headers need to be set in
    HttpConnection.
  • You need to change the request method by calling
    setRequestMethod() and the header by calling
    setRequestProperty().
  • Obtain the output stream for the HttpConnection
    by calling openOutputStream().
  • Send the request parameters on the output stream
    returned from the HttpConnection.
  • Parameters should be encoded as described earlier

32
Example Login - Post Method
  • The only difference is in the run method. Other
    methods are the same as the previous example.
  • public void run()
  • String name userName.getString()
  • String pwd password.getString()
  • StringBuffer b new StringBuffer("")
  • HttpConnection hc null
  • InputStream in null
  • OutputStream out null
  • String parameter
  • String result
  • String url "http//ictlab.tyict.vtc.edu.
    hk/nelsonc/mobile/"

  • "login_post_demo.php?"
  • parameter "name" name
  • parameter "password" pwd.replace('
    ', '')

33
Example Login - Post Method
  • try
  • hc (HttpConnection)Connector.open(ur
    l)
  • hc.setRequestMethod(HttpConnection.POS
    T)
  • hc.setRequestProperty("CONTENT-TYPE",
  • "application/x-www-fo
    rm-urlencoded")
  • hc.setRequestProperty("User-Agent",
  • "Profile/MIDP-2.0
    Configuration/CLDC-1.0")
  • out hc.openOutputStream()
  • byte postmsg parameter.getBytes(
    )
  • for(int i0iltpostmsg.lengthi)
  • out.write(postmsgi)
  • out.flush()
  • in hc.openInputStream()
  • int ch
  • // same as before ....

34
Read Binary Data From Network
  • The data read from server is already in binary
    format.
  • The following program (ImageLoader.java) reads an
    image file from a web server and display it as an
    ImageItem.

35
Example - ImageLoader
  • import java.io.
  • import javax.microedition.io.
  • import javax.microedition.lcdui.
  • import javax.microedition.midlet.
  • public class ImageLoader extends MIDlet
  • implements CommandListener, Runnable
  • private Display mDisplay
  • private Form mForm
  • public ImageLoader()
  • mForm new Form("Connecting...")
  • mForm.addCommand(new Command("Exit",
    Command.EXIT, 0))
  • mForm.setCommandListener(this)

36
Example - ImageLoader
  • public void startApp()
  • if (mDisplay null) mDisplay
    Display.getDisplay(this)
  • mDisplay.setCurrent(mForm)
  • // Do network loading in a separate
    thread.
  • Thread t new Thread(this)
  • t.start()
  • public void pauseApp()
  • public void destroyApp(boolean unconditional)
  • public void commandAction(Command c,
    Displayable s)
  • if (c.getCommandType() Command.EXIT)
  • notifyDestroyed()

37
Example - ImageLoader
  • public void run()
  • HttpConnection hc null
  • DataInputStream in null
  • try
  • String url
  • "http//ictlab.tyict.vtc.edu.hk/
    nelsonc/mobile/ive_ty.png"
  • hc (HttpConnection)
    Connector.open(url)
  • int length (int)hc.getLength()
  • byte data null
  • if (length ! -1)
  • data new bytelength
  • in new DataInputStream(hc.openIn
    putStream())
  • in.readFully(data)
  • else
  • throw new IOException("Unable to
    determine the length")

38
Example - ImageLoader
  • Image image Image.createImage(data,
    0, length)
  • ImageItem imageItem new
    ImageItem(null, image, 0, null)
  • mForm.append(imageItem)
  • mForm.setTitle("Done.")
  • catch (IOException ioe)
  • StringItem stringItem new
    StringItem(null, ioe.toString())
  • mForm.append(stringItem)
  • mForm.setTitle("Done.")
  • finally
  • try
  • if (in ! null) in.close()
  • if (hc ! null) hc.close()
  • catch (IOException ioe)
  • ioe.printStackTrace()

39
Using HTTPS
  • HTTP is not a secure protocol.
  • A more secure alternative, HTTPS, runs atop
    Transport Layer Security (TLS), Secure Sockets
    Layer (SSL), or a similar protocol.
  • In typical TLS interactions, the server sends a
    certificate to the client to authenticate itself.
  • The client must have Certificate Authority (CA)
    root certificates on hand to verify the server's
    certificate.
  • If the client can verify the certificate, the
    client will then send a secret value to the
    server, encrypted with the server's public key.

40
Using HTTPS
  • The server and the client both derive a session
    key from this secret value, which is used to
    encrypt all subsequent traffic sent between the
    client and server.
  • The generic connection framework makes it very
    easy to obtain HTTPS connections.
  • All you have to do is construct an HTTPS
    connection string. So instead of this
  • HttpConnection hc (HttpConnection)
    Connector.open("http//www.cert.org/")
  • You would do this
  • HttpConnection hc (HttpConnection)
    Connector.open("https//www.cert.org/")
  • It's really that simple.
Write a Comment
User Comments (0)
About PowerShow.com