MIDP Programming Networking. Chapter Objectives The CLDC Streams Model Generic Connection Framework (GCF) Supported Protocols Creating a Connection Review.

Slides:



Advertisements
Similar presentations
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Advertisements

 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Network Programming Chapter 11 Lecture 6. Networks.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
10-Jun-15 Servlets. 2 Servers A server is a computer that responds to requests from a client Typical requests: provide a web page, upload or download.
Prepared By E. Musa Alyaman1 URLs, InetAddresses, and URLConnections Chapter 9.
An introduction to Java Servlet Programming
16-Jun-15 HTTP Hypertext Transfer Protocol. 2 HTTP messages HTTP is the language that web clients and web servers use to talk to each other HTTP is largely.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
13-Jul-15 Servlets. 2 Servers A server is a computer that responds to requests from a client Typical requests: provide a web page, upload or download.
13-Jul-15 Sockets and URLs. 2 Sockets A socket is a low-level software device for connecting two computers together Sockets can also be used to connect.
HTTP Overview Vijayan Sugumaran School of Business Administration Oakland University.
Hypertext Transport Protocol CS Dick Steflik.
 What is it ? What is it ?  URI,URN,URL URI,URN,URL  HTTP – methods HTTP – methods  HTTP Request Packets HTTP Request Packets  HTTP Request Headers.
PL-IV- Group A HTTP Request & Response Header
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Comp2513 Forms and CGI Server Applications Daniel L. Silver, Ph.D.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
HyperText Transfer Protocol (HTTP).  HTTP is the protocol that supports communication between web browsers and web servers.  A “Web Server” is a HTTP.
27.1 Chapter 27 WWW and HTTP Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
TCP/IP Protocol Suite 1 Chapter 22 Upon completion you will be able to: World Wide Web: HTTP Understand the components of a browser and a server Understand.
Application Protocols: HTTP CSNB534 Semester 2, 2007/2008 Asma Shakil.
Maryam Elahi University of Calgary – CPSC 441.  HTTP stands for Hypertext Transfer Protocol.  Used to deliver virtually all files and other data (collectively.
Java Omar Rana University of South Asia. Course Overview JAVA  C/C++ and JAVA Comparison  OOP in JAVA  Exception Handling  Streams  Graphics User.
HTTP HTTP stands for Hypertext Transfer Protocol. It is an TCP/IP based communication protocol which is used to deliver virtually all files and other.
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of socket.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
CSCI 7010 UGA March 23 rd,  BES/MDS  TCP/IP  BIS  WiFi  WAP 2.0  WAP 1.0.
Copyright, 1996 © Dale Carnegie & Associates, Inc. Presented by Hsiuling Hsieh Christine Liu.
MIDP Programming Networking Khanh Le. / 2 of Chapter Objectives The CLDC Streams Model Generic Connection Framework (GCF) Supported Protocols Creating.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
Programming Handheld and Mobile devices 1 Programming of Handheld and Mobile Devices Lecture 15 IO Using http Rob Pooley
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
Java Servlet API CGI / HTTP Concepts Java Servlet API.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
Operating Systems Lesson 12. HTTP vs HTML HTML: hypertext markup language ◦ Definitions of tags that are added to Web documents to control their appearance.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
27.1 Chapter 27 WWW and HTTP Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
27.1 Chapter 27 WWW and HTTP Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Overview of Servlets and JSP
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
How CGI and Java Servlets are Run By David Stein 14 November 2006.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Chapter 4 Request and Response. Servlets are controlled by the container.
Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Introduction to Servlets
Tiny http client and server
Building Web Apps with Servlets
Sockets and URLs 17-Sep-18.
Sockets and URLs 13-Nov-18.
Servlet.
Chapter 26 Servlets.
Generating the Server Response: HTTP Status Codes
URL in Java C343 Lab (Week 13).
Sockets and URLs 3-Dec-18.
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
HTTP Hypertext Transfer Protocol
Presentation transcript:

MIDP Programming Networking

Chapter Objectives The CLDC Streams Model Generic Connection Framework (GCF) Supported Protocols Creating a Connection Review of HTTP Making an HTTP Request Building a CGI String Design Tips Differences between J2ME and J2SE Networking

The CLDC Streams Model In MIDP, as in J2SE, IO streams are the primary mechanism available to applications to read and write streams of data. In addition to java.io, the MIDP defines the javax.microedition.io package in contrast to java.net, which supports networking and communications for MIDP applications. MIDP applications use the javax.microedition.io types to create and manipulate various kinds of network connections. They then read from these connections and write to them using the types in the MIDP java.io package, which contains a subset of the classes and interfaces in the J2SE java.io package.

Generic Connection Framework CLDC specifies a generic connection mechanism Leaves considerable flexibility to implementations Capable of supporting many different kinds of connections, from serial ports through wireless networking The fundamental idea: Give an URL-like string to the framework Get back something that has input and output streams

Connection and its Family Connection represents some kind of I/O connection It has subinterfaces that define more specific connection types

Making a Connection Connector is a Connection factory Pass a URL-style string to open(), get back some Connection implementation MIDP says that HTTP must be supported Other connection types are optional Note that HTTP does not have to run over TCP/IP

Connection protocol support Connector.Open("socket://

Opening a connection public static Connection open(String name) public static Connection open(String name, int mode) public static Connection open(String name, int mode, boolean timeouts)

Opening a connection public static DataInputStream openDataInputStream(String name) public static DataOutputStream openDataOutputStream(String name) public static InputStream openInputStream(String name) public static OutputStream openOutputStream(String name)

Opening a connection //Create connection ContentConnection connection = (ContentConnection) Connector.open(" ); // With the connection, open a stream InputStream iStrm = connection.openInputStream(); // ContentConnection includes a length method int length = (int) connection.getLength(); if (length != -1) { byte imageData[] = new byte[length]; // Read the data into an array iStrm.read(imageData);}

Opening a connection InputStream iStrm = (InputStream) Connector.openInputStream(url); Image img = null; ByteArrayOutputStream bStrm = new ByteArrayOutputStream(); int ch; while ((ch = iStrm.read()) != -1) { bStrm.write(ch); // Place into image array byte imageData[] = bStrm.toByteArray(); // Create the image from the byte array img = Image.createImage(imageData, 0, imageData.length); }

HTTP support in MIDP

The original MIDP 1.0 specification only required that devices support the HTTP connection protocol MIDP 2.0 spec requires support for both HTTP and HTTPS. The APIs to work with these protocols are HttpConnection and HttpConnections, respectively

Request and response protocols Both HTTP and HTTPS are request/response protocols. A client sends a request and a server sends a response

Request and response protocols The client request, sometimes called the request entity, consists of the following three sections: Request method HeaderBody

Request and response protocols The request method determines how data will be sent to a remote resource. The three methods available are: GET: data is sent as part of the URL. POST: any client data is sent in a separate stream, distinct from the request to establish a connection. HEADER: requests do not send any data to a server. Instead, HEADER requests only meta information about the remote resource

Request and response protocols String url = " HttpConnection http = (HttpConnection) Connector.open(url); http.setRequestMethod(HttpConnection.GET);

Request and response protocols Header fields let us pass parameters, if you will, from the client to the server. Common fields are If-Modified-Since, Accept, and User Agent. You set header fields as key-value pairs, using the setRequestProperty() method

Request and response protocols String url = " HttpConnection http = (HttpConnection) Connector.open(url); http.setRequestMethod(HttpConnection.GET); // Set header field as key-value pair http.setRequestProperty("If-Modified-Since", "Mon, 12 Jan :00:00 GMT");

Request and response protocols String url = “ String tmp = "test data here"; OutputStream ostrm = null; HttpConnection http = null; http = (HttpConnection) Connector.open(url); http.setRequestMethod(HttpConnection.POST); //Send client body ostrm = http.openOutputStream(); byte bytes[] = tmp.getBytes(); for(int i = 0; i < bytes.length; i++) { os.write(bytes[i]);}os.flush();

Request and response protocols After the server has received and processed the client request, it must package and send a response. As with the client request, three sections are associated with the server response: Status line HeaderBody

Request and response protocols Status line: the server status line informs the client of the outcome of its request. HTTP classifies the status line codes into the following broad categories: 1xx is informational 2xx is success 3xx is redirection 4xx is client error 5xx is server error

Request and response protocols "HTTP/ OK" "HTTP/ Bad Request" "HTTP/ Internal Server Error"

Request and response protocols The server can send information through header fields. Three of the most common methods for retrieving header information sent from a server String getHeaderField(int n) String getHeaderField(String name) String getHeaderFieldKey(int n)

Request and response protocols the response in a server header contained the content "content-type=text/plain"the response in a server header contained the content "content-type=text/plain" Method Return value http.getHeaderField(0)"text-plain" http.getHeaderField("content-type")"text-plain" http.getHeaderFieldKey(0)"content-type"

The HttpConnection API MethodDescription long getDate() Get header field date long getExpiration() Gets header field expiration String getFile() Gets filename from the URL int getHeaderField(int n) Gets header field value looking up by index String getHeaderField( String name) Gets header field value looking up by name

Request and response protocols MethodDescription int getHeaderFieldInt(String name, int def) Gets named field as an integer String getHeaderFieldKey(int n) Gets header field key using index String getHost() Gets host from the URL String getPort() Gets port from the URL void setRequestMethod( String method) Sets the request method (GET, POST or HEAD) String getProtocol() Gets protocol from the URL

Request and response protocols MethodDescription String getQuery() Gets the query string String getRequestMethod() Gets the current setting of the request method int getResponseCode() Gets the response code String getURL() Gets the entire URL String getResponseMessage() Gets the response message

Accessing a Java servlet private void callServlet() throws IOException { HttpConnection http = null; InputStream iStrm = null; boolean ret = false; // Examples - Data is passed at the end of url for GET String url = " format=MMMM.dd.yyyy+'-'+hh:mm+aa"; http = (HttpConnection) Connector.open(url); // 1) Send request method http.setRequestMethod(HttpConnection.GET); // 2) Send header information - none // 3) Send body/data - data is at the end of URL iStrm = http.openInputStream(); // Three steps are processed in this method call ret = processServerResponse(http, iStrm); }

Accessing a Java servlet private boolean processServerResponse(HttpConnection http, InputStream iStrm) { // 1) Get status Line if (http.getResponseCode() == HttpConnection.HTTP_OK) { // 2) Get header information - none // 3) Get body (data) int length = (int) http.getLength(); String str; if (length != -1) { byte servletData[] = new byte[length]; iStrm.read(servletData); str = new String(servletData); } else { // Length not available... ByteArrayOutputStream bStrm = new ByteArrayOutputStream(); int ch; while ((ch = iStrm.read()) != -1) bStrm.write(ch); str = new String(bStrm.toByteArray()); } serverMsg = str; // Save the server message return true; } return false; }

Accessing a Java servlet public class DateFormatServlet extends HttpServlet { public void init(ServletConfig config) throws ServletException { super.init(config);} public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String format = request.getParameter("format"); SimpleDateFormat simpleDate = new SimpleDateFormat(format); Date dt = new Date(); PrintWriter out = response.getWriter(); response.setContentType("text/html");out.println(simpleDate.format(dt));out.close();} public String getServletInfo() { return "DateFormatServlet"; }}

Review of HTTP General data transfer protocol Client sends request Server sends response Requests and responses have two parts: Headers (metadata) Content Requests often have no content Requests can contain parameters Think of the values from an HTML form

HTTP Connections The MIDP profile supports HTTP version 1.1 connections via the HttpConnection interface. The GET, POST, and HEAD schemes of HTTP are supported.

Parameters For GET, parameters are encoded and tacked on to the end of the URL athan&zip=08540 With POST, parameters are sent as the content part of the request The same encoding is used

Performing a GET It’s amazingly simple: String url = " InputConnection ic = (InputConnection)Connector.open(url); InputStream in = ic.openInputStream(); // Now read stuff from the InputStream. // Remember to clean up. ic.close(); Remember to catch IOExceptions

GET Example

POSTing a Form It’s a little more complicated than GET You need HttpConnection methods Change the request method with setRequestMethod() Tell the server the length of your parameters (“Content-Length”) with setRequestProperty() Send the parameters in the output stream of the connection of the connection See Jargoneer.java

POST Example

Invoking a CGI Script Both the GET and POST methods can be used to invoke a CGI (Common Gateway Interface) scripts and supply input data

Design Tips Use GET instead of POST Don’t hard-code URLs Network access should go in its own thread Handle exceptions gracefully Clean up

Differences between J2ME and J2SE Networking There's no MIDP java.net package as there is in J2SE. MIDP java.io package only supports a subset of the familiar J2SE byte- and character-oriented input and output stream classes. The following application-level facilities are missing from the MIDP: RMI requires too much processing for mobile devices to support at this time. Jini requires RMI; therefore, it's not present. JavaSpaces doesn't exist in J2ME. CORBA middleware doesn't exist in J2ME.