SlideShare a Scribd company logo
Outline-session 12 (21-April-2009) >> GCF(Generic Connection Framework) -Connection Hierarchy -HTTP Connection -Creating a Connection -Client Request -Server Response -Connection Information -Get and POST with JavaServlet and JDBC.
Connection Hierarchy >> Weighing in at nearly 200 kilobytes, the 100+ classes and interfaces in J2SE java.io and java.net will exceed the resources available on many mobile devices. >> To provide an extensible framework for i/o and networking, the GCF was developed. >> one class, the Connector, that can create any type of connection >> file, http, datagram, and so forth >> open method has the following form. Connector.Open("protocol:address;parameters") Examples: >>Connector.Open("http://www.some_web_address.com"); >>Connector.Open("socket://someaddress:1234"); >>Connector.Open("file://testdata.txt");
Connection Hierarchy >> How the protocols are resolved is where the flexibility of the GCF comes into play. >> At runtime,Connector looks for the appropriate class that implements the requested protocol. >> This is done using Class.forName() >> file, http, datagram, and so forth >> A request to open a HTTP connection in J2ME Class.forName("com.sun.midp.io.j2me.http.Protocol");  >> an object is returned that implements a Connection interface >> The Connector class and Connection interfaces are defined in CLDC
Connection Hierarchy >> >> The actual implementation of the protocol(s) is at the Profile level. >> HttpConnection extends ContentConnection and in turn provides over 20 methods for working specifically with HTTP.
Connection Hierarchy  Connection (public abstract interface Connection) public void close() InputConnection (public abstract interface InputConnection extends Connection) public InputStream openInputStream() public DataInputStream openDataInputStream() OutputConnection (public abstract interface OutputConnection extends Connection) public OutputStream openOutputStream() public DataOutputStream openDataOutputStream() StreamConnection (public abstract interface StreamConnection extends InputConnection,OutputConnection) ContentConnection (public abstract interface ContentConnection extends Stream  Connection) public long getLength() public String getEncoding() public String getType() HttpConnection (public interface HttpConnection extends ContentConnection) Connector (public class Connector) public static Connection open(String name) public static Connection open(String name, int mode) public static Connection open(String name, int mode, boolean timeouts) public static DataInputStream openDataInputStream(String name) public static DataOutputStream openDataOutputStream(String name) public static InputStream openInputStream(String name) public static OutputStream openOutputStream(String name)
HTTP Connection >>   In MIDP 1.0 the only protocol that is guaranteed to be implemented is http >> Through the class HttpConnection you can communicate with a web server or any remote device that supports HTTP >>HTTP Operation: -HTTP is Known as Request/Response Protocol -A client Initiate the request ,send to the server with an address specified as a Uniform Resource Locater -Server send the response back.
Creating Connection >>Connecter method has seven method to create connection with a server. >>There are three variation of methods. The first requires only the address of the server second method accepts a mode for reading/writing The third option includes a Boolean flag that indicates if the caller of the method can manage timeout exceptions The remaining methods open various input and output streams. >>Implementation // Create a ContentConnection String url = "http://www.corej2me.com" ContentConnection  connection =(ContentConnection) Connector.open(url); InputStream iStrm = connection.openInputStream();int length = (int) connection.getLength(); if (length > 0){byte imageData[] = new byte[length];// Read the data into an array iStrm.read(imageData);}
CLDC Connector Method and Modes
CLDC Connector Method and Modes >>  Sample ViewPng.java –using ContentConnection >> Sample ViewPng2.java- Using InputStream
Client Request >> HTTP is referred to as a request/response protocol >>A client requests information, a server sends a response >>The most common example is the interaction between a web browser (the client) and a web server Request Method >> Client request , known as  the request entity, consist of three Section -Request Method -Request Header -Request Body >>There are three request methods are available they are -Get
Client Request >>GET and POST, what differs is how data from the client is transferred to the server >>HttpConnection http = null; http = (HttpConnection) Connector.open(url); http.setRequestMethod(HttpConnection.GET);
Client Request Using GET >>Using GET, the body (data) of the request becomes part of the URL >>URL Form  http://www.corej2me.com/formscript?userColor=blue&userFont=courier >>Notice the "?" after the URL. This signifies the end of the URL and start of the form data. All information is sent through "key-value" pairs such as userColor=blue, userFont=courier. [5]Multiple key-value pairs are separated with "&". Using POST >>Data submitted using POST is sent separately from the call to the URL. >>The request to open a connection to a URL is sent as one stream, any data is sent as a separate stream >>There are two major benefits of POST over GET POST has no limit to the amount of data that can be sent POST sends data as a separate stream; therefore, the contents are not visible as part of the URL.
Client Request Header Information >> The second part of a client request is header information >> The HTTP protocol defines over 40 header fields >> Some of the more common are Accept, Cache-Control, Content-Type, Expires, If-Modified-Since and User-Agent >> Headers are set by calling setRequestProperty(). HttpConnection http = null;http = (HttpConnection) Connector.open(url); http.setRequestMethod(HttpConnection.GET); http.setRequestProperty("If-Modified-Since“, "Mon, 16 Jul 2001 22:54:26 GMT"); Body >>  Data to be transferred from the client to the server is referred to as the body of the request >> GET sends the body as part of the URL. POST sends the body in a separate stream
Server Response >>Once a client has packaged together the request method, header and body, and sent it over the network >>it is now up to the server to interpret the request and generate a response known as the response entity >>client request, a server response consists of three sections status line, header and  Body Status Line >>The status line indicates the outcome of the client request >>For HttpConnection, there are over 35 status codes reported >>HTTP divides the codes into three broad categories based on the numeric value mapped to the code
Server Response Status Line 1xx—information 2xx—success 3xx—redirection 4xx—client errors 5xx—server errors >>When sending a response, a server includes the protocol version number along with the status code. HTTP/1.1 200 OK HTTP/1.1 400 Bad Request HTTP/1.1 500 Internal Server Error >>http.getResponseMessage(); >>http.getResponseCode();
Server Response Header  >>Like the client, the server can send information through a header >>These key-value pairs can be retrieved in various shapes and forms through the methods >> >>// Header field at index 0: "content-type=text/plain" http.getHeaderField(0); // "text-plain" http.getHeaderField("content-type"); // "text-plain" http.getHeaderFieldKey(0); // "content-type"
Server Response Body >>The body is the data sent from the server to the client >>There are no methods defined in HttpConnection for reading the body >>The most common means to obtain the body is through a stream >> Example: Download a File url = http://www.corej2me.com/midpbook_v1e1/ch14/getHeaderInfo.txt"; HttpConnection http = null;…// Create the connection http = (HttpConnection) Connector.open(url); The client request is straightforward: //----------------// Client Request//---------------- // 1) Send request method http.setRequestMethod(HttpConnection.GET); // 2) Send header information (this header is optional) http.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0"); // 3) Send body/data - No data for this request
Server Response Server Response //----------------// Server Response//----------------//  1) Get status Line System.out.println("Msg: " + http.getResponseMessage()); System.out.println("Code: " + http.getResponseCode()); // 2) Get header information if (http.getResponseCode() == HttpConnection.HTTP_OK) { System.out.println("field 0: " + http.getHeaderField(0)); ... System.out.println("key 0: " + http.getHeaderFieldKey(0)); ... System.out.println("content: " + http.getHeaderField("content-type")); ...
Server Response Server Response 3) Get data (show the file contents) String str;iStrm = http.openInputStream();int length = (int) http.getLength();if (length != -1){// Read data in one chunkbyte serverData[] = new byte[length]; iStrm.read(serverData);str = new String(serverData);} else // Length not available... { ByteArrayOutputStream bStrm = new ByteArrayOutputStream(); // Read data one character at a time int ch; while ((ch = iStrm.read()) != -1) bStrm.write(ch); str = new String(bStrm.toByteArray()); bStrm.close(); }System.out.println("File Contents: " + str);}
Connection Information Introduction: >> Once a connection has been established, there are several methods available to obtain information about the connection. System.out.println("Host: " + http.getHost());System.out.println("Port: " + http.getPort());System.out.println("Type: " + http.getType()); Host: www.corej2me.com Post: 80 Type: plain/text
Get and POST to Java Servlet and JDBC Introduction: >> Constructing a client request using GET and POST are different enough to warrant an example >> will connect with a Java servlet to look up a bank account balance Client Request >> The main Form will hold two TextFields, an account number and password >> Once the form has been completed and the user chooses the "Menu" option, there will be a choice as to the request method for sending the data >> The account information will be stored in a database, named acctInfo, located on the same machine as the servlet. >> The database, acctInfo,will contain three columns (account, password, balance)
Using Get Method // Data is passed at the end of url for GET String url ="http://www.mycgiserver.com/servlet/corej2me.GetNpostServlet" + "?" +"account=" + tfAcct.getString() + "&" +"password=" + tfPwd.getString();try{ http = (HttpConnection) Connector.open(url); //----------------// Client Request//---------------- // 1) Send request method http.setRequestMethod(HttpConnection.GET); // 2) Send header information - none // 3) Send body/data - data is at the end of URL //----------------// Server Response//---------------- iStrm = http.openInputStream(); // Three steps are processed in this method call ret = processServerResponse(http, iStrm); }
Using POST Method // Data is passed as a separate stream for POST (below) String url ="http://www.mycgiserver.com/servlet/corej2me.GetNpostServlet"; Try{http = (HttpConnection) Connector.open(url);oStrm = http.openOutputStream();//----------------// Client Request // 1) Send request type http.setRequestMethod(HttpConnection.POST); // 2) Send header information. Required for POST to work http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 3) Send data // Write account number byte data[] = ("account=" + tfAcct.getString()).getBytes(); oStrm.write(data); // Write password data = ("&password=" + tfPwd.getString()).getBytes(); oStrm.write(data); oStrm.flush(); //----------------// Server Response//---------------- iStrm = http.openInputStream(); // Three steps are processed in this method call ret = processServerResponse(http, iStrm); } -
Server Response A servlet will run one of two methods, depending on whether the client request method is GET or POST. doGet(HttpServletRequest req, HttpServletResponse res) doPost(HttpServletRequest req, HttpServletResponse res) >> how the servlet looks up information in the account database private String accountLookup(String acct, String pwd) { // These will vary depending on your server/database Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:acctInfo"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select balance from acctInfo where account = " + acct + "and password = '" + pwd + "'"); if (rs.next()) return rs.getString(1); else return null; ... } -
Updating the Client Now that the client has sent a request and the server has responded, the MIDlet needs to interpret the server reply and update the display with the account balance. processServerResponse(HttpConnection http, InputStream iStrm) { //Reset error messageerrorMsg = null;// 1) Get status Lineif (http.getResponseCode() == HttpConnection.HTTP_OK) { // 2) Get header information - none // 3) Get body (data)int length = (int) http.getLength(); if (length > 0) {byte servletData[] = new byte[length];iStrm.read(servletData); // Update the string item on the displaysiBalance.setText(new String(servletData)); return true;} else errorMsg = new String("Unable to read data"); } else // Use message from the servlet errorMsg = new String(http.getResponseMessage()); return false; } -
Ad

More Related Content

What's hot (20)

SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
Sourabh Sahu
 
Bootstrap Web Development Framework
Bootstrap Web Development FrameworkBootstrap Web Development Framework
Bootstrap Web Development Framework
Cindy Royal
 
Fragment
Fragment Fragment
Fragment
nationalmobileapps
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
Aakash Ugale
 
Java basic
Java basicJava basic
Java basic
Sonam Sharma
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Quiz app (android) Documentation
Quiz app (android) DocumentationQuiz app (android) Documentation
Quiz app (android) Documentation
Aditya Nag
 
Mobile Application Development,J2ME,UNIT-4-JNTU
Mobile Application Development,J2ME,UNIT-4-JNTUMobile Application Development,J2ME,UNIT-4-JNTU
Mobile Application Development,J2ME,UNIT-4-JNTU
Pallepati Vasavi
 
android sqlite
android sqliteandroid sqlite
android sqlite
Deepa Rani
 
StringTokenizer in java
StringTokenizer in javaStringTokenizer in java
StringTokenizer in java
Muthukumaran Subramanian
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
Android Networking
Android NetworkingAndroid Networking
Android Networking
Maksym Davydov
 
Chat Application
Chat ApplicationChat Application
Chat Application
kuldip kumar
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
shanmuga rajan
 
java mini project for college students
java mini project for college students java mini project for college students
java mini project for college students
SWETALEENA2
 
JDBC
JDBCJDBC
JDBC
People Strategists
 
Android UI
Android UIAndroid UI
Android UI
nationalmobileapps
 
Database in Android
Database in AndroidDatabase in Android
Database in Android
MaryadelMar85
 
Software requirement Analysis (SRS) for FACEBOOK
Software requirement Analysis (SRS) for FACEBOOKSoftware requirement Analysis (SRS) for FACEBOOK
Software requirement Analysis (SRS) for FACEBOOK
Krishna Mohan Mishra
 
Bootstrap Web Development Framework
Bootstrap Web Development FrameworkBootstrap Web Development Framework
Bootstrap Web Development Framework
Cindy Royal
 
Data Storage In Android
Data Storage In Android Data Storage In Android
Data Storage In Android
Aakash Ugale
 
Quiz app (android) Documentation
Quiz app (android) DocumentationQuiz app (android) Documentation
Quiz app (android) Documentation
Aditya Nag
 
Mobile Application Development,J2ME,UNIT-4-JNTU
Mobile Application Development,J2ME,UNIT-4-JNTUMobile Application Development,J2ME,UNIT-4-JNTU
Mobile Application Development,J2ME,UNIT-4-JNTU
Pallepati Vasavi
 
android sqlite
android sqliteandroid sqlite
android sqlite
Deepa Rani
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
java mini project for college students
java mini project for college students java mini project for college students
java mini project for college students
SWETALEENA2
 
Software requirement Analysis (SRS) for FACEBOOK
Software requirement Analysis (SRS) for FACEBOOKSoftware requirement Analysis (SRS) for FACEBOOK
Software requirement Analysis (SRS) for FACEBOOK
Krishna Mohan Mishra
 

Similar to Session12 J2ME Generic Connection Framework (20)

Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
WebStackAcademy
 
SCWCD 2. servlet req - resp (cap3 - cap4)
SCWCD 2. servlet   req - resp (cap3 - cap4)SCWCD 2. servlet   req - resp (cap3 - cap4)
SCWCD 2. servlet req - resp (cap3 - cap4)
Francesco Ierna
 
Introduction To ASP.NET MVC
Introduction To ASP.NET MVCIntroduction To ASP.NET MVC
Introduction To ASP.NET MVC
Alan Dean
 
Spring MVC 3 Restful
Spring MVC 3 RestfulSpring MVC 3 Restful
Spring MVC 3 Restful
knight1128
 
WCF - In a Week
WCF - In a WeekWCF - In a Week
WCF - In a Week
gnanaarunganesh
 
Wsdl
WsdlWsdl
Wsdl
sanmukundan
 
WWW and HTTP
WWW and HTTPWWW and HTTP
WWW and HTTP
BG Java EE Course
 
AJAX
AJAXAJAX
AJAX
Gouthaman V
 
AJAX
AJAXAJAX
AJAX
Gouthaman V
 
KMUTNB - Internet Programming 2/7
KMUTNB - Internet Programming 2/7KMUTNB - Internet Programming 2/7
KMUTNB - Internet Programming 2/7
phuphax
 
RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座
Li Yi
 
Servlet Part 2
Servlet Part 2Servlet Part 2
Servlet Part 2
vikram singh
 
JSP diana y yo
JSP diana y yoJSP diana y yo
JSP diana y yo
michael
 
SCWCD : The web client model
SCWCD : The web client modelSCWCD : The web client model
SCWCD : The web client model
Ben Abdallah Helmi
 
Ajax presentation
Ajax presentationAjax presentation
Ajax presentation
engcs2008
 
Scmad Chapter09
Scmad Chapter09Scmad Chapter09
Scmad Chapter09
Marcel Caraciolo
 
SCWCD : The web client model : CHAP : 1
SCWCD  : The web client model : CHAP : 1SCWCD  : The web client model : CHAP : 1
SCWCD : The web client model : CHAP : 1
Ben Abdallah Helmi
 
Basics Of Servlet
Basics Of ServletBasics Of Servlet
Basics Of Servlet
Shubhani Jain
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2
Ben Abdallah Helmi
 
Living in the Cloud: Hosting Data & Apps Using the Google Infrastructure
Living in the Cloud: Hosting Data & Apps Using the Google InfrastructureLiving in the Cloud: Hosting Data & Apps Using the Google Infrastructure
Living in the Cloud: Hosting Data & Apps Using the Google Infrastructure
Pamela Fox
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
WebStackAcademy
 
SCWCD 2. servlet req - resp (cap3 - cap4)
SCWCD 2. servlet   req - resp (cap3 - cap4)SCWCD 2. servlet   req - resp (cap3 - cap4)
SCWCD 2. servlet req - resp (cap3 - cap4)
Francesco Ierna
 
Introduction To ASP.NET MVC
Introduction To ASP.NET MVCIntroduction To ASP.NET MVC
Introduction To ASP.NET MVC
Alan Dean
 
Spring MVC 3 Restful
Spring MVC 3 RestfulSpring MVC 3 Restful
Spring MVC 3 Restful
knight1128
 
KMUTNB - Internet Programming 2/7
KMUTNB - Internet Programming 2/7KMUTNB - Internet Programming 2/7
KMUTNB - Internet Programming 2/7
phuphax
 
RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座
Li Yi
 
JSP diana y yo
JSP diana y yoJSP diana y yo
JSP diana y yo
michael
 
Ajax presentation
Ajax presentationAjax presentation
Ajax presentation
engcs2008
 
SCWCD : The web client model : CHAP : 1
SCWCD  : The web client model : CHAP : 1SCWCD  : The web client model : CHAP : 1
SCWCD : The web client model : CHAP : 1
Ben Abdallah Helmi
 
SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2SCWCD : The servlet model CHAP : 2
SCWCD : The servlet model CHAP : 2
Ben Abdallah Helmi
 
Living in the Cloud: Hosting Data & Apps Using the Google Infrastructure
Living in the Cloud: Hosting Data & Apps Using the Google InfrastructureLiving in the Cloud: Hosting Data & Apps Using the Google Infrastructure
Living in the Cloud: Hosting Data & Apps Using the Google Infrastructure
Pamela Fox
 
Ad

More from muthusvm (14)

Java 7 Language Enhancement
Java 7 Language EnhancementJava 7 Language Enhancement
Java 7 Language Enhancement
muthusvm
 
Session13 J2ME Timer
Session13  J2ME TimerSession13  J2ME Timer
Session13 J2ME Timer
muthusvm
 
Session11 J2ME Record Management System Database
Session11 J2ME Record Management System DatabaseSession11 J2ME Record Management System Database
Session11 J2ME Record Management System Database
muthusvm
 
Session11 J2ME MID-Low Level User Interface(LLUI)-graphics
Session11 J2ME MID-Low Level User Interface(LLUI)-graphicsSession11 J2ME MID-Low Level User Interface(LLUI)-graphics
Session11 J2ME MID-Low Level User Interface(LLUI)-graphics
muthusvm
 
Session11 J2ME Record Management System
Session11 J2ME Record Management SystemSession11 J2ME Record Management System
Session11 J2ME Record Management System
muthusvm
 
Session10 J2ME Record Management System
Session10 J2ME Record Management SystemSession10 J2ME Record Management System
Session10 J2ME Record Management System
muthusvm
 
Session8 J2ME Low Level User Interface
Session8 J2ME Low Level User InterfaceSession8 J2ME Low Level User Interface
Session8 J2ME Low Level User Interface
muthusvm
 
Session7 J2ME High Level User Interface(HLUI) part1-2
Session7 J2ME High Level User Interface(HLUI) part1-2Session7 J2ME High Level User Interface(HLUI) part1-2
Session7 J2ME High Level User Interface(HLUI) part1-2
muthusvm
 
Session6 J2ME High Level User Interface(HLUI) part1
Session6 J2ME High Level User Interface(HLUI) part1Session6 J2ME High Level User Interface(HLUI) part1
Session6 J2ME High Level User Interface(HLUI) part1
muthusvm
 
Session5 J2ME High Level User Interface(HLUI) part1
Session5 J2ME High Level User Interface(HLUI) part1Session5 J2ME High Level User Interface(HLUI) part1
Session5 J2ME High Level User Interface(HLUI) part1
muthusvm
 
Session4 J2ME Mobile Information Device Profile(MIDP) Events
Session4 J2ME Mobile Information Device Profile(MIDP) EventsSession4 J2ME Mobile Information Device Profile(MIDP) Events
Session4 J2ME Mobile Information Device Profile(MIDP) Events
muthusvm
 
Session2-J2ME development-environment
Session2-J2ME development-environmentSession2-J2ME development-environment
Session2-J2ME development-environment
muthusvm
 
Session1 j2me introduction
Session1  j2me introductionSession1  j2me introduction
Session1 j2me introduction
muthusvm
 
Session 3 J2ME Mobile Information Device Profile(MIDP) API
Session 3 J2ME Mobile Information Device Profile(MIDP)  APISession 3 J2ME Mobile Information Device Profile(MIDP)  API
Session 3 J2ME Mobile Information Device Profile(MIDP) API
muthusvm
 
Java 7 Language Enhancement
Java 7 Language EnhancementJava 7 Language Enhancement
Java 7 Language Enhancement
muthusvm
 
Session13 J2ME Timer
Session13  J2ME TimerSession13  J2ME Timer
Session13 J2ME Timer
muthusvm
 
Session11 J2ME Record Management System Database
Session11 J2ME Record Management System DatabaseSession11 J2ME Record Management System Database
Session11 J2ME Record Management System Database
muthusvm
 
Session11 J2ME MID-Low Level User Interface(LLUI)-graphics
Session11 J2ME MID-Low Level User Interface(LLUI)-graphicsSession11 J2ME MID-Low Level User Interface(LLUI)-graphics
Session11 J2ME MID-Low Level User Interface(LLUI)-graphics
muthusvm
 
Session11 J2ME Record Management System
Session11 J2ME Record Management SystemSession11 J2ME Record Management System
Session11 J2ME Record Management System
muthusvm
 
Session10 J2ME Record Management System
Session10 J2ME Record Management SystemSession10 J2ME Record Management System
Session10 J2ME Record Management System
muthusvm
 
Session8 J2ME Low Level User Interface
Session8 J2ME Low Level User InterfaceSession8 J2ME Low Level User Interface
Session8 J2ME Low Level User Interface
muthusvm
 
Session7 J2ME High Level User Interface(HLUI) part1-2
Session7 J2ME High Level User Interface(HLUI) part1-2Session7 J2ME High Level User Interface(HLUI) part1-2
Session7 J2ME High Level User Interface(HLUI) part1-2
muthusvm
 
Session6 J2ME High Level User Interface(HLUI) part1
Session6 J2ME High Level User Interface(HLUI) part1Session6 J2ME High Level User Interface(HLUI) part1
Session6 J2ME High Level User Interface(HLUI) part1
muthusvm
 
Session5 J2ME High Level User Interface(HLUI) part1
Session5 J2ME High Level User Interface(HLUI) part1Session5 J2ME High Level User Interface(HLUI) part1
Session5 J2ME High Level User Interface(HLUI) part1
muthusvm
 
Session4 J2ME Mobile Information Device Profile(MIDP) Events
Session4 J2ME Mobile Information Device Profile(MIDP) EventsSession4 J2ME Mobile Information Device Profile(MIDP) Events
Session4 J2ME Mobile Information Device Profile(MIDP) Events
muthusvm
 
Session2-J2ME development-environment
Session2-J2ME development-environmentSession2-J2ME development-environment
Session2-J2ME development-environment
muthusvm
 
Session1 j2me introduction
Session1  j2me introductionSession1  j2me introduction
Session1 j2me introduction
muthusvm
 
Session 3 J2ME Mobile Information Device Profile(MIDP) API
Session 3 J2ME Mobile Information Device Profile(MIDP)  APISession 3 J2ME Mobile Information Device Profile(MIDP)  API
Session 3 J2ME Mobile Information Device Profile(MIDP) API
muthusvm
 
Ad

Recently uploaded (20)

UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 

Session12 J2ME Generic Connection Framework

  • 1. Outline-session 12 (21-April-2009) >> GCF(Generic Connection Framework) -Connection Hierarchy -HTTP Connection -Creating a Connection -Client Request -Server Response -Connection Information -Get and POST with JavaServlet and JDBC.
  • 2. Connection Hierarchy >> Weighing in at nearly 200 kilobytes, the 100+ classes and interfaces in J2SE java.io and java.net will exceed the resources available on many mobile devices. >> To provide an extensible framework for i/o and networking, the GCF was developed. >> one class, the Connector, that can create any type of connection >> file, http, datagram, and so forth >> open method has the following form. Connector.Open("protocol:address;parameters") Examples: >>Connector.Open("http://www.some_web_address.com"); >>Connector.Open("socket://someaddress:1234"); >>Connector.Open("file://testdata.txt");
  • 3. Connection Hierarchy >> How the protocols are resolved is where the flexibility of the GCF comes into play. >> At runtime,Connector looks for the appropriate class that implements the requested protocol. >> This is done using Class.forName() >> file, http, datagram, and so forth >> A request to open a HTTP connection in J2ME Class.forName("com.sun.midp.io.j2me.http.Protocol"); >> an object is returned that implements a Connection interface >> The Connector class and Connection interfaces are defined in CLDC
  • 4. Connection Hierarchy >> >> The actual implementation of the protocol(s) is at the Profile level. >> HttpConnection extends ContentConnection and in turn provides over 20 methods for working specifically with HTTP.
  • 5. Connection Hierarchy Connection (public abstract interface Connection) public void close() InputConnection (public abstract interface InputConnection extends Connection) public InputStream openInputStream() public DataInputStream openDataInputStream() OutputConnection (public abstract interface OutputConnection extends Connection) public OutputStream openOutputStream() public DataOutputStream openDataOutputStream() StreamConnection (public abstract interface StreamConnection extends InputConnection,OutputConnection) ContentConnection (public abstract interface ContentConnection extends Stream Connection) public long getLength() public String getEncoding() public String getType() HttpConnection (public interface HttpConnection extends ContentConnection) Connector (public class Connector) public static Connection open(String name) public static Connection open(String name, int mode) public static Connection open(String name, int mode, boolean timeouts) public static DataInputStream openDataInputStream(String name) public static DataOutputStream openDataOutputStream(String name) public static InputStream openInputStream(String name) public static OutputStream openOutputStream(String name)
  • 6. HTTP Connection >> In MIDP 1.0 the only protocol that is guaranteed to be implemented is http >> Through the class HttpConnection you can communicate with a web server or any remote device that supports HTTP >>HTTP Operation: -HTTP is Known as Request/Response Protocol -A client Initiate the request ,send to the server with an address specified as a Uniform Resource Locater -Server send the response back.
  • 7. Creating Connection >>Connecter method has seven method to create connection with a server. >>There are three variation of methods. The first requires only the address of the server second method accepts a mode for reading/writing The third option includes a Boolean flag that indicates if the caller of the method can manage timeout exceptions The remaining methods open various input and output streams. >>Implementation // Create a ContentConnection String url = "http://www.corej2me.com" ContentConnection connection =(ContentConnection) Connector.open(url); InputStream iStrm = connection.openInputStream();int length = (int) connection.getLength(); if (length > 0){byte imageData[] = new byte[length];// Read the data into an array iStrm.read(imageData);}
  • 9. CLDC Connector Method and Modes >> Sample ViewPng.java –using ContentConnection >> Sample ViewPng2.java- Using InputStream
  • 10. Client Request >> HTTP is referred to as a request/response protocol >>A client requests information, a server sends a response >>The most common example is the interaction between a web browser (the client) and a web server Request Method >> Client request , known as the request entity, consist of three Section -Request Method -Request Header -Request Body >>There are three request methods are available they are -Get
  • 11. Client Request >>GET and POST, what differs is how data from the client is transferred to the server >>HttpConnection http = null; http = (HttpConnection) Connector.open(url); http.setRequestMethod(HttpConnection.GET);
  • 12. Client Request Using GET >>Using GET, the body (data) of the request becomes part of the URL >>URL Form http://www.corej2me.com/formscript?userColor=blue&userFont=courier >>Notice the "?" after the URL. This signifies the end of the URL and start of the form data. All information is sent through "key-value" pairs such as userColor=blue, userFont=courier. [5]Multiple key-value pairs are separated with "&". Using POST >>Data submitted using POST is sent separately from the call to the URL. >>The request to open a connection to a URL is sent as one stream, any data is sent as a separate stream >>There are two major benefits of POST over GET POST has no limit to the amount of data that can be sent POST sends data as a separate stream; therefore, the contents are not visible as part of the URL.
  • 13. Client Request Header Information >> The second part of a client request is header information >> The HTTP protocol defines over 40 header fields >> Some of the more common are Accept, Cache-Control, Content-Type, Expires, If-Modified-Since and User-Agent >> Headers are set by calling setRequestProperty(). HttpConnection http = null;http = (HttpConnection) Connector.open(url); http.setRequestMethod(HttpConnection.GET); http.setRequestProperty("If-Modified-Since“, "Mon, 16 Jul 2001 22:54:26 GMT"); Body >> Data to be transferred from the client to the server is referred to as the body of the request >> GET sends the body as part of the URL. POST sends the body in a separate stream
  • 14. Server Response >>Once a client has packaged together the request method, header and body, and sent it over the network >>it is now up to the server to interpret the request and generate a response known as the response entity >>client request, a server response consists of three sections status line, header and Body Status Line >>The status line indicates the outcome of the client request >>For HttpConnection, there are over 35 status codes reported >>HTTP divides the codes into three broad categories based on the numeric value mapped to the code
  • 15. Server Response Status Line 1xx—information 2xx—success 3xx—redirection 4xx—client errors 5xx—server errors >>When sending a response, a server includes the protocol version number along with the status code. HTTP/1.1 200 OK HTTP/1.1 400 Bad Request HTTP/1.1 500 Internal Server Error >>http.getResponseMessage(); >>http.getResponseCode();
  • 16. Server Response Header >>Like the client, the server can send information through a header >>These key-value pairs can be retrieved in various shapes and forms through the methods >> >>// Header field at index 0: "content-type=text/plain" http.getHeaderField(0); // "text-plain" http.getHeaderField("content-type"); // "text-plain" http.getHeaderFieldKey(0); // "content-type"
  • 17. Server Response Body >>The body is the data sent from the server to the client >>There are no methods defined in HttpConnection for reading the body >>The most common means to obtain the body is through a stream >> Example: Download a File url = http://www.corej2me.com/midpbook_v1e1/ch14/getHeaderInfo.txt"; HttpConnection http = null;…// Create the connection http = (HttpConnection) Connector.open(url); The client request is straightforward: //----------------// Client Request//---------------- // 1) Send request method http.setRequestMethod(HttpConnection.GET); // 2) Send header information (this header is optional) http.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0"); // 3) Send body/data - No data for this request
  • 18. Server Response Server Response //----------------// Server Response//----------------// 1) Get status Line System.out.println("Msg: " + http.getResponseMessage()); System.out.println("Code: " + http.getResponseCode()); // 2) Get header information if (http.getResponseCode() == HttpConnection.HTTP_OK) { System.out.println("field 0: " + http.getHeaderField(0)); ... System.out.println("key 0: " + http.getHeaderFieldKey(0)); ... System.out.println("content: " + http.getHeaderField("content-type")); ...
  • 19. Server Response Server Response 3) Get data (show the file contents) String str;iStrm = http.openInputStream();int length = (int) http.getLength();if (length != -1){// Read data in one chunkbyte serverData[] = new byte[length]; iStrm.read(serverData);str = new String(serverData);} else // Length not available... { ByteArrayOutputStream bStrm = new ByteArrayOutputStream(); // Read data one character at a time int ch; while ((ch = iStrm.read()) != -1) bStrm.write(ch); str = new String(bStrm.toByteArray()); bStrm.close(); }System.out.println("File Contents: " + str);}
  • 20. Connection Information Introduction: >> Once a connection has been established, there are several methods available to obtain information about the connection. System.out.println("Host: " + http.getHost());System.out.println("Port: " + http.getPort());System.out.println("Type: " + http.getType()); Host: www.corej2me.com Post: 80 Type: plain/text
  • 21. Get and POST to Java Servlet and JDBC Introduction: >> Constructing a client request using GET and POST are different enough to warrant an example >> will connect with a Java servlet to look up a bank account balance Client Request >> The main Form will hold two TextFields, an account number and password >> Once the form has been completed and the user chooses the "Menu" option, there will be a choice as to the request method for sending the data >> The account information will be stored in a database, named acctInfo, located on the same machine as the servlet. >> The database, acctInfo,will contain three columns (account, password, balance)
  • 22. Using Get Method // Data is passed at the end of url for GET String url ="http://www.mycgiserver.com/servlet/corej2me.GetNpostServlet" + "?" +"account=" + tfAcct.getString() + "&" +"password=" + tfPwd.getString();try{ http = (HttpConnection) Connector.open(url); //----------------// Client Request//---------------- // 1) Send request method http.setRequestMethod(HttpConnection.GET); // 2) Send header information - none // 3) Send body/data - data is at the end of URL //----------------// Server Response//---------------- iStrm = http.openInputStream(); // Three steps are processed in this method call ret = processServerResponse(http, iStrm); }
  • 23. Using POST Method // Data is passed as a separate stream for POST (below) String url ="http://www.mycgiserver.com/servlet/corej2me.GetNpostServlet"; Try{http = (HttpConnection) Connector.open(url);oStrm = http.openOutputStream();//----------------// Client Request // 1) Send request type http.setRequestMethod(HttpConnection.POST); // 2) Send header information. Required for POST to work http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 3) Send data // Write account number byte data[] = ("account=" + tfAcct.getString()).getBytes(); oStrm.write(data); // Write password data = ("&password=" + tfPwd.getString()).getBytes(); oStrm.write(data); oStrm.flush(); //----------------// Server Response//---------------- iStrm = http.openInputStream(); // Three steps are processed in this method call ret = processServerResponse(http, iStrm); } -
  • 24. Server Response A servlet will run one of two methods, depending on whether the client request method is GET or POST. doGet(HttpServletRequest req, HttpServletResponse res) doPost(HttpServletRequest req, HttpServletResponse res) >> how the servlet looks up information in the account database private String accountLookup(String acct, String pwd) { // These will vary depending on your server/database Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:acctInfo"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select balance from acctInfo where account = " + acct + "and password = '" + pwd + "'"); if (rs.next()) return rs.getString(1); else return null; ... } -
  • 25. Updating the Client Now that the client has sent a request and the server has responded, the MIDlet needs to interpret the server reply and update the display with the account balance. processServerResponse(HttpConnection http, InputStream iStrm) { //Reset error messageerrorMsg = null;// 1) Get status Lineif (http.getResponseCode() == HttpConnection.HTTP_OK) { // 2) Get header information - none // 3) Get body (data)int length = (int) http.getLength(); if (length > 0) {byte servletData[] = new byte[length];iStrm.read(servletData); // Update the string item on the displaysiBalance.setText(new String(servletData)); return true;} else errorMsg = new String("Unable to read data"); } else // Use message from the servlet errorMsg = new String(http.getResponseMessage()); return false; } -