- Overview
- Network Programming with J2SE Versus J2ME
- The Generic Connection Framework
- Wireless Network Programming Using Sockets
- Wireless Network Programming Using Datagrams
- Wireless Network Programming Using HttpConnection
- Summary
Wireless Network Programming Using HttpConnection
The section "Wireless Network Programming Using Sockets," showed an example of using socket connections to communicate with a Web server using the HTTP protocol. The same thing can be done more easily with the HttpConnection, which is more closely tied to the HTTP protocol for communicating with Web servers. It defines several HTTP-specific methods to make HTTP-based network programming simpler and more straightforward. For example, HttpConnection provides methods that allow developers to obtain HTTP header information much easier.
Using HttpConnection as the network communication in your application offers several major advantages:
Not every MIDP device supports socket and datagram communication. However, all MIDP devices support HTTP communication.
Socket and datagram communications are very network dependent. Some networks may implement only one type of communication and not the other. This limitation makes your wireless application less portable.
The mandatory support of the HTTP protocol in MIDP devices gives wireless application a high-level, standard, network-independent protocol to work with. Therefore, J2ME wireless applications developed using HttpConnection are very portable across different wireless networks.
Different types of data can be encapsulated into HTTP requests easily, especially if developers use XML in their applications. Chapter 10, "Using XML in Wireless Applications," discusses in more detail how to use XML in wireless application development. HTTP communication makes it easier to deal with issues such as network security and firewalls. Because the HTTP's well-known port 80 is the least likely port blocked by firewalls.
Methods in HttpConnection
The HttpConnection interface supports a subset of the HTTP 1.1 protocol. Here are the methods defined in HttpConnection:
long getDate()
This method returns the value of the date field in the HTTP header. The result is the number of milliseconds since January 1, 1970, GMT.
long getExpiration()
This method returns the value of the expires field in the HTTP header. The result is the number of milliseconds since January 1, 1970, GMT. It returns 0 if the value is unknown.
String getFile()
This method returns the file portion of the URL of this HttpConnection. It returns null if there is no file.
String getHeaderField(int index)
This method returns the String value of a header field by index. It returns null if index is out of range. Because the HTTP headers returned by different Web servers are different, it is recommended that you check to see if the value is null before applying any operation on it. You have to know the sequence of the header fields to use this method.
String getHeaderField(String name)
This method returns the String value of a named header field. It returns null if the field is missing or malformed.
long getHeaderFieldDate(String name, long def)
This method returns the long value of a named header field. The value is parsed as a date. The result is the number of milliseconds since January 1, 1970, GMT. The default value def is returned if the field is missing or malformed.
int getHeaderFieldInt(String name, int def)
This method returns the int value of a named header field. The default value def is returned if the field is missing or malformed.
String getHeaderFieldKey(int index)
This method returns the name of a header field by index. It returns null if index is out of range. You have to know the sequence of the header fields to use this method.
String getHost()
This method returns the host information of the URL string.
long getLastModified()
This method returns the value of the last-modified field in the HTTP header. The result is the number of milliseconds since January 1, 1970, GMT. It returns 0 if the value is unknown.
int getPort()
This method returns the port number of the URL string. It returns 80 by default if there was no port number in the string passed to Connector.open().
String getProtocol()
This method returns the protocol name of the URL string, such as http or https.
String getQuery()
This method returns the query portion of the URL string. In the HTTP protocol, a query component of a URL is defined as the text after the last question mark (?) character in the URL. For instance, the query portion of the URL string http://64.28.105.110/servlets/webyu/Chapter9Servlet?request=gettimestamp is request=gettimestamp.
String getRef()
This method returns the reference portion of the URL string. In the HTTP protocol, a reference component of a URL is defined as the text after the crosshatch character (#) in the URL. For instance, the reference portion of the URL string http://64.28.105.110/index.html#top is top.
String getRequestMethod()
This method returns the current request method of the HttpConnection. The possible values are GET, HEAD, and POST.
String getRequestProperty(String key)
This method returns the value of the general request property by the key property.
int getResponseCode()
This method returns the HTTP response status code. For instance
HTTP/1.1 200 OK HTTP/1.1 401 Unauthorized
The method returns the integers 200 and 401, respectively, from the above responses.
String getResponseMessage()
This method returns the HTTP response message from a Web server. For instance, given the responses HTTP/1.1 200 OK and HTTP/1.1 401 Unauthorized, the method returns the strings OK and Unauthorized, respectively.
String getURL()
This method returns the URL string of this HttpConnection.
void setRequestMethod(String method)
This method sets the request method for this HttpConnection. The possible values are GET, POST, and HEAD. If not specified, the default HTTP request method is GET.
void setRequestProperty(String key, String value)
This method sets the general request property for this HttpConnection. For instance
setRequestProperty( "User-Agent", "Mozilla/5.001 (windows; U; NT4.0; en-us) Gecko/25250101");
sets a value for the request property "User-Agent" of an HttpConnection. If a property with the key already exists, the method overwrites its value with the new value.
The following methods are inherited from the ContentConnection interface:
String getEncoding() long getLength() String getType() DataInputStream openDataInputStream() InputStream openInputStream() DataOutputStream openDataOutputStream() OutputStream openOutputStream()
HttpConnection States
There are two possible states for an HTTP connection: Setup and Connected.
In the Setup state, the connection has not been made to the server. In the Connected state, the connection has been made, request parameters have been sent, and the response is expected in the Connected state.
The transition from the Setup state to the Connected state is caused by any method that requires data to be sent to or received from the server. The following methods cause the transition to the Connected state from a Setup state:
openInputStream() openDataInputStream() openOutputStream() openDataOutputStream() oetLength() oetType() oetEncoding() getDate() getExpiration() getLastModified() getHeaderField() getHeaderFieldKey() getResponseCode() getResponseMessage() getHeaderFieldInt() getHeaderFieldDate()
The following methods may be invoked only in the Setup state:
setRequestMethod() setRequestProperty()
The following methods may be invoked in any state:
close() getRequestMethod() getRequestProperty() getURL() getProtocol() getHost() getFile() getRef() getPort() getQuery()
HttpConnection Request Methods
HttpConnection allows three types of requests to be sent to a Web server: GET, HEAD, and POST.
The GET method is used by programs to obtain the contents of a Web document from the specified URL. The Web server responses consist of HTTP header information about the Web document, MIME type information about the content data, and the actual content data.
The HEAD method is used by programs to obtain information about a Web document instead of retrieving the contents of the Web document. When the Web server receives a HEAD request, only the HTTP header data (without the content data) is returned.
The POST method is often used by programs to send the form information to the URL of a CGI program. Both POST and GET can be used to send data to a CGI program; the difference is that the POST method sends data via a stream while the GET method sends data via environment variables embedded in the query string.
The following examples explain how to use these request methods with HttpConnection.
Using the GET Request Method with HttpConnection
The default request method used by HttpConnection is GET. This type of request carries all the information as part of the URL string. In the following code example, a GET request is sent to server 64.28.105.110:
http://64.28.105.110/servlets/webyu/Chapter9Servlet?request=gettimestamp
The Java servlet Chapter9Servlet will accept the request, get the current local time, and send it back to the client.
In a GET request, the query string is embedded as part of the URL string. For instance, if getQuery() is called on this HTTP connection, the value request=gettimestamp will be returned. When the GET request is sent to the Java servlet, the previous environment variable request and its value are also passed along to the server program.
Listing 9.7 is a sample program that demonstrates how to send a GET request to a Web server using HttpConnection.
Listing 9.7 HttpGET.java
/** * The following MIDlet application demonstrates how to establish a * HttpConnection and uses it to send a GET request to Web server. */ // include MIDlet class libraries import javax.microedition.midlet.*; // include networking class libraries import javax.microedition.io.*; // include GUI class libraries import javax.microedition.lcdui.*; // include I/O class libraries import java.io.*; public class HttpGET extends MIDlet implements CommandListener { // A default URL is used. User can change it from the GUI. private static String defaultURL = "http://64.28.105.110/servlets/webyu/Chapter9Servlet?request=gettimestamp"; // GUI components for entering a Web URL. private Display myDisplay = null; private Form mainScreen; private TextField requestField; // GUI components for displaying server responses. private Form resultScreen; private StringItem resultField; // the "send" button used on mainScreen Command sendCommand = new Command("SEND", Command.OK, 1); // the "back" button used on resultScreen Command backCommand = new Command("BACK", Command.OK, 1); public HttpGET(){ // initialize the GUI components myDisplay = Display.getDisplay(this); mainScreen = new Form("Type in a URL:"); requestField = new TextField(null, defaultURL, 100, TextField.URL); mainScreen.append(requestField); mainScreen.addCommand(sendCommand); mainScreen.setCommandListener(this); } public void startApp() { myDisplay.setCurrent(mainScreen); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable s) { // when user clicks on the "send" button on mainScreen if (c == sendCommand) { // retrieve the Web url that user entered String urlstring = requestField.getString(); // send a GET request to Web server String resultstring = ""; try { resultstring = sendGetRequest(urlstring); } catch (IOException e) { resultstring = "ERROR"; } // display the page content retrieved from Web server resultScreen = new Form("GET Result:"); resultField = new StringItem(null, resultstring); resultScreen.append(resultField); resultScreen.addCommand(backCommand); resultScreen.setCommandListener(this); myDisplay.setCurrent(resultScreen); } else if (c == backCommand) { // do it all over again requestField.setString(defaultURL); myDisplay.setCurrent(mainScreen); } } // send a GET request to Web server public String sendGetRequest(String urlstring) throws IOException { HttpConnection hc = null; DataInputStream dis = null; String message = ""; try { // open up an HttpConnection with the Web server // the default request method is GET. hc = (HttpConnection) Connector.open(urlstring); // obtain a DataInputStream from the HttpConnection dis = new DataInputStream(hc.openInputStream()); // retrieve the contents of the requested page from Web server int ch; while ((ch = dis.read()) != -1) { message = message + (char) ch; } } finally { if (hc != null) hc.close(); if (dis != null) dis.close(); } return message; } }
Figure 9.9 shows a screenshot of the HttpGET program before the GET request is sent out to a Web server.
Figure 9.10 shows a screenshot of the page content retrieved from a Web URL.
Figure 9.9 Type in the Web URL.
Figure 9.10 The content of a Web document.
Using the HEAD Request Method with HttpConnection
HTTP servers provide a substantial amount of information in the HTTP headers that precede each response. For instance, here's a typical HTTP header returned by an Apache Web server running on Sun Solaris:
HTTP 1.1 200 OK Data: Mon, 18 Oct 1999 20:06:48 GMT Server: Apache/1.3.4 (Unix) PHP/3.0.6 Last-Modified: Mon, 18 Oct 1999 Accept-Ranges: bytes Content-Length: 35259 Content-Type: text/html
In most cases, an HTTP header includes the content type of the page requested, the content length and the character set in which the content is encoded, the date and time of the response, the last modified time of the page requested, and the expiration date for caching purposes. The following are some of the most common header fields in an HTTP header:
Content-type Content-length Content-encoding Date Last-modified Expires
When a HEAD request is sent to a Web server, only the header information will be returned. This type of request is typically used to determine if a cache entry can be reused or if it should be replaced with newer information based on the property values retrieved from the header fields.
The sample program in Listing 9.8 sends a HEAD request to Web server 64.28.105.110 and retrieves all the HTTP header information. The setRequestMethod(HttpConnection.HEAD) method is used to specify that this request is a HEAD request. The getHeaderField() method is used to retrieve the field values and the getHeaderFieldKey() method is used to retrieve the field names.
Listing 9.8 HttpHEAD.java
/** * The following MIDlet application demonstrates how to establish * an HttpConnection and use it to send a HEAD request * to a Web server. */ import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; import java.io.*; public class HttpHEAD extends MIDlet implements CommandListener { // A default URL is used. User can change it from the GUI. private static String defaultURL = "http://64.28.105.110"; // GUI components for entering a Web URL. private Display myDisplay = null; private Form mainScreen; private TextField requestField; // GUI components for displaying server responses. private Form resultScreen; private StringItem resultField; // the "send" button used on mainScreen Command sendCommand = new Command("SEND", Command.OK, 1); // the "back" button used on resultScreen Command backCommand = new Command("BACK", Command.OK, 1); public HttpHEAD(){ // initialize the GUI components myDisplay = Display.getDisplay(this); mainScreen = new Form("Type in a URL:"); requestField = new TextField( null, defaultURL, 50, TextField.URL); mainScreen.append(requestField); mainScreen.addCommand(sendCommand); mainScreen.setCommandListener(this); } public void startApp() { myDisplay.setCurrent(mainScreen); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command c, Displayable s) { // when user clicks on the "send" button if (c == sendCommand) { // retrieve the Web URL that user entered String urlstring = requestField.getString(); // send a HEAD request to Web server String resultstring = ""; try{ resultstring = sendHeadRequest(urlstring); } catch (IOException e) { resultstring = "ERROR"; } // display the header information retrieved from Web server resultScreen = new Form("HEAD Result:"); resultField = new StringItem(null, resultstring); resultScreen.append(resultField); resultScreen.addCommand(backCommand); resultScreen.setCommandListener(this); myDisplay.setCurrent(resultScreen); } else if (c == backCommand) { // do it all over again requestField.setString(defaultURL); myDisplay.setCurrent(mainScreen); } } // send a HEAD request to Web server public String sendHeadRequest(String urlstring) throws IOException { HttpConnection hc = null; InputStream is = null; String message = ""; try { // open up an HttpConnection with the Web server hc = (HttpConnection) Connector.open(urlstring); // set request method to HEAD hc.setRequestMethod(HttpConnection.HEAD); // obtain an InputStream from the HttpConnection is = hc.openInputStream(); // retrieve the value pairs of HTTP header information int i = 1; String key = ""; String value = ""; while ((value = hc.getHeaderField(i)) != null) { key = hc.getHeaderFieldKey(i++); message = message + key + ":" + value + "\n"; } } finally { if (hc != null) hc.close(); if (is != null) is.close(); } return message; } }
Figure 9.11 shows a screenshot of all the header information retrieved from a Web server.
Several additional methods are available in HttpConnection for retrieving header information: getLength, getType, getEncoding, getResponseCode, getResponseMessage, getHeaderFieldInt, and getHeaderFieldDate.
Using the POST Request Method with HttpConnection
To send an HTTP request using the POST method, both InputStream and OutputStream have to be obtained from the HttpConnection. InputStream will be used to retrieve the responses from the Web server. OutputStream will be used to send the data separately via a stream (in our examples, the data to be sent is request=gettimestamp).
The following MIDlet application is very similar to HttpGET.java, except that the request being sent is a POST request. The Web URL is
http://64.28.105.110/servlets/webyu/Chapter9Servlet
Figure 9.11 Header information retrieved by the program HttpHEAD.java.
The Java servlet Chapter9Servlet will accept this request, get the local current time, and send it back to the client. Notice that in this POST request, the data to be sent request=gettimestamp is no longer part of the URL. It will be sent to Web server separately once the HTTP connection is established.
Listing 9.9 demonstrates how to send a POST request to a Web server using HttpConnection.
Listing 9.9 HttpPOST.java
/** * This MIDlet application demonstrates how to establish * an HttpConnection and use it to send a POST request * to a Web server. */ import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.io.*; import java.io.*; public class HttpPOST extends MIDlet implements CommandListener { // A default URL is used. User can change it from the GUI. private static String defaultURL = "http://64.28.105.110/servlets/webyu/Chapter9Servlet"; // GUI component for entering a Web URL private Display myDisplay = null; private Form mainScreen; private TextField requestField; // GUI component for displaying server responses. private Form resultScreen; private StringItem resultField; // the "send" button used on mainScreen Command sendCommand = new Command("SEND", Command.OK, 1); // the "back" button used on resultScreen Command backCommand = new Command("BACK", Command.OK, 1); public HttpPOST(){ // initialize the GUI components myDisplay = Display.getDisplay(this); mainScreen = new Form("Type in a URL:"); requestField = new TextField(null, defaultURL, 100, TextField.URL); mainScreen.append(requestField); mainScreen.addCommand(sendCommand); mainScreen.setCommandListener(this); } public void startApp() { myDisplay.setCurrent(mainScreen); } public void pauseApp() { } public void destroyApp(boolean unconditional) { // help Garbage Collector Display myDisplay = null; mainScreen = null; requestField = null; resultScreen = null; resultField = null; } public void commandAction(Command c, Displayable s) { // when user clicks on the "send" button if (c == sendCommand) { // retrieve the Web URL that user entered String urlstring = requestField.getString(); // send a POST request to Web server String resultstring = ""; try { resultstring = sendPostRequest(urlstring); } catch (IOException e) { resultstring = "ERROR"; } // display the message received from Web server resultScreen = new Form("POST Result:"); resultField = new StringItem(null, resultstring); resultScreen.append(resultField); resultScreen.addCommand(backCommand); resultScreen.setCommandListener(this); myDisplay.setCurrent(resultScreen); } else if (c == backCommand) { // do it all over again requestField.setString(defaultURL); myDisplay.setCurrent(mainScreen); } } // send a POST request to Web server public String sendPostRequest(String urlstring) throws IOException { HttpConnection hc = null; DataInputStream dis = null; DataOutputStream dos = null; String message = ""; // the request body String requeststring = "request=gettimestamp"; try { // an HttpConnection with both read and write access hc = (HttpConnection) Connector.open(urlstring, Connector.READ_WRITE); // set the request method to POST hc.setRequestMethod(HttpConnection.POST); // obtain DataOutputStream for sending the request string dos = hc.openDataOutputStream(); byte[] request_body = requeststring.getBytes(); // send request string to Web server for (int i = 0; i < request_body.length; i++) { dos.writeByte(request_body[i]); } // flush it out dos.flush(); // obtain DataInputStream for receiving server responses dis = new DataInputStream(hc.openInputStream()); // retrieve the responses from Web server int ch; while ((ch = dis.read()) != -1) { message = message + (char) ch; } } finally { // free up i/o streams and http connection if (hc != null) hc.close(); if (dis != null) dis.close(); if (dos != null) dos.close(); } return message; } }
When the sample program HttpPOST.java runs successfully, it should generate the same result as shown in Figure 9.9.
Server-Side Handling of GET and POST Requests
The requests sent by both HttpGET.java and HttpPOST.java are handled by a single Java servlet Chapter9Servlet on http://www.webyu.com. The responses to these requests are identical even though they are handled differently inside the servlet.
Network programming with J2ME typically involves both client and server programs. Due to the limited resources available on wireless, most of J2ME clients are thin clients. This means that complex business logic and heavy computation will be left to the servers. Server-side programming is as important as client-side programming, if not more so. It is beneficial to understand how HTTP's GET and POST requests are handled on the Web server side.
Listing 9.10 is the Java servlet that handles the HTTP requests sent by HttpGET.java and HttpPOST.java.
Listing 9.10 Chapter9Servlet.java
/** * Chapter9Servlet is a Java servlet running at * http://www.webyu.com/servlets/webyu/Chatper9Servlet. * It responds to both GET and POST requests. The request * message must be "request=gettimestamp". The response * message is a current timestamp. */ import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Chapter9Servlet extends HttpServlet{ public void init (ServletConfig config) throws ServletException { super.init(config); } // doGet will be called when a GET request is received. public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // get field value in the query string String value = request.getParameter("request"); // turn auto flush on PrintWriter out = new PrintWriter( response.getOutputStream(), true); // call getResult to get the current timestamp String message = getResult(value); // send an HTML response back to the client response.setContentType("text/html"); response.setContentLength(message.length()); out.println(message); } // doPost will be called when a POST request is received. public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = ""; String value = ""; // parse out the value pair from the POST body // the expected string is "request=gettimestamp" try { BufferedReader br = request.getReader(); String line; String requeststring = ""; while (( line = br.readLine()) != null) { requeststring = requeststring + line; } StringTokenizer sTokenizer = new StringTokenizer(requeststring, "="); if (sTokenizer.hasMoreTokens()) name = (String) sTokenizer.nextToken(); if (sTokenizer.hasMoreTokens()) value = (String) sTokenizer.nextToken(); } catch (Exception e) { System.err.println(e); } // turn auto flush on PrintWriter out = new PrintWriter(response.getOutputStream(), true); String message = getResult(value); response.setContentType("text/html"); response.setContentLength(message.length()); out.println(message); } //get current timestamp and put it into HTML format public String getResult(String method) { String message = ""; // if the query string value is "gettimestamp" //then current local timestamp is returned if ( method.equals("gettimestamp") ) { TimeZone timezone = TimeZone.getDefault(); Calendar calendar = Calendar.getInstance(timezone); String local_time = calendar.getTime().toString(); message = message + "<html><head><title>" + local_time + "</title></head>\n"; message = message + "<body>Web Server's Local Time is <br>\n"; message = message + local_time + "</body></html>\n"; } else { // otherwise, an error message is returned message = message + "<html><head><title>Error</title></head>\n"; message = message + "<body>Unrecoganized Method Name</body></html>\n"; } return message; } }
In Chapter9Servlet.java, the doGet() method is called when GET requests are received, and the doPost() method is called when POST requests are received. In the doGet() method, the environment variable request is retrieved by calling the getParameter("request") method. While in the doPost() method, the data chunk request=timestamp is retrieved via a BufferedReader. Compiling and running this server program requires Java servlet and Web server knowledge and is beyond the scope of this book. For more information about Java servlets, please visit Sun's Java Web site at http://www.javasoft.com.