Network Programming: Part I (General Techniques) : For Live Android Training, Please See Courses
Network Programming: Part I (General Techniques) : For Live Android Training, Please See Courses
Network Programming: Part I (General Techniques) : For Live Android Training, Please See Courses
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Spring, Hibernate/JPA, EJB3, GWT, Hadoop, SOAP-based and RESTful Web Services
Contact hall@coreservlets.com for details Developed and taught by well-known author and developer. At public venues or onsite at your location.
Socket basics Requesting Internet permission Example: NIST atomic time Aside: simple String formatting and parsing Example: FTP welcome messages Example: validating URLs with HEAD HttpURLConnection HttpClient Examples: Searching Web pages Using JSON Example: remote loan calculations Example: Google translation services
Overview
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Big Idea
Many ways to communicate with a server
Socket class
Lets you do general-purpose network programming
Same as with desktop Java programming
HttpURLConnection
Simplifies connections to HTTP servers
Same as with desktop Java programming
HttpClient
Simplest way to download entire content of a URL
Not standard in Java SE, but standard in Android
JSONObject
Simplifies creation and parsing of JSON data
7
Socket Basics
Developed and taught by well-known author and developer. At public venues or onsite at your location.
For input stream, BufferedReader, call read to get a single char or an array of characters, or call readLine to get a whole line
Note that readLine returns null if the connection was terminated (i.e. on EOF), but waits otherwise
You can use ObjectInputStream and ObjectOutputStream for Java-to-Java communication. Very powerful and simple.
Exceptions
UnknownHostException
If host passed to Socket constructor is not known to DNS server.
Note that you may use an IP address string for the host
IOException
Timeout Connection refused by server Interruption or other unexpected problem
Server closing connection does not cause an error when reading: null is returned from readLine
11
Code
public class SocketUtils { public static BufferedReader getReader(Socket s) throws IOException { return(new BufferedReader (new InputStreamReader(s.getInputStream()))); }
public static PrintWriter getWriter(Socket s) throws IOException { // Second argument of true means autoflush. return (new PrintWriter(s.getOutputStream(), true)); } }
12
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://" > <uses-sdk android:minSdkVersion="" /> <uses-permission android:name="android.permission.INTERNET" /> </manifest>
13
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Approach
15
Make a Socket connection to time-b.nist.gov on port 13 Create a BufferedReader (no PrintWriter needed) Read first line of result and ignore it Read second line of result and print it out
16
17
Values Files
res/values/strings.xml
Defines title, prompts, and button labels for all Activities in this section.
Used in both portrait and landscape mode.
res/values/colors.xml
Defines foreground color for some of the results
Used in both portrait and landscape mode.
res/values/dimens.xml
Gives font sizes.
Used in portrait mode.
res/values-land/dimens.xml
Gives font sizes.
18
19
Results
21
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Approach
Formatting requests
Use printf (aka String.format)
Advantages
Lets you insert values into output without much clumsier String concatenation. Lets you control the width of results so things line up Lets you control the number of digits after the decimal point in numbers, for consistent-looking output
public static void printSomeStrings() { String firstName = "John"; String lastName = "Doe"; int numPets = 7; String petType = "chickens"; System.out.printf("%s %s has %s %s.%n", firstName, lastName, numPets, petType); System.out.println(firstName + " " + lastName + " has " + numPets + " " + petType + "."); }
Result:
25
Controlling Formatting
Different flags
%s for strings, %f for floats/doubles, %t for dates, etc.
Unlike in C/C++, you can use %s for any type (even nums)
To control width, number of digits, commas, justification, type of date format, and more printf uses mini-language
Complete coverage would take an entire lecture However, basic usage is straightforward
http://download.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
Using + instead of , between arguments (printf uses varargs) Forgetting to add %n at the end if you want a newline (not automatic)
Options
%widths Gives min num of chars. Spaces added to left if needed. %widthd %,widthd Gives min width; inserts commas.
Example
printf("%8s", "Hi") outputs " Hi"
%tx
printf("%,9d", 1234) outputs " 1,234" Floating point. Lets you line %width.precisionf printf("%6.2f", Math.PI) up decimal point and control %,width.precisionf outputs precision. width includes comma and " 3.14" decimal point. Time (or date). %tA for day, Date now = new Date(); %tB for month, %tY for year, printf("%tA, %tB ,%tY", now, now, now) and many more. outputs "Thursday, November 17, 2005" Outputs OS-specific end of line (linefeed on Linux/Unix, CR/LF pair on Windows)
27
%n
28
Note that you cannot make a class with a main method in an Android app and run it from Eclipse in the usual way (R-click, Run As Java Application). So, the printf and parsing examples are in a separate project called NetworkingSupport. This project also contains the servlet used in the second networking lecture.
29
30
StringTokenizer
Constructors
StringTokenizer(String input, String delimiters) StringTokenizer(String input, String delimiters, boolean includeDelimiters) StringTokenizer(String input)
Default delimiter set is " \t\n\r\f" (whitespace)
Methods
nextToken(), nextToken(String delimiters) countTokens() hasMoreTokens()
33
Tutorials
http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#sum
http://download.oracle.com/javase/tutorial/essential/regex/
35
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Approach
Connect to server on port 21 and read first line
If it does not start with "220-", print it and exit
If first line does start with "220-", read and echo lines until you find one that starts with "220 ".
39
ftp.oracle.com
> ftp ftp.oracle.com 220-*********************************************************************** 220-Oracle FTP Server 220220-The use of this FTP server is governed by United States Export Admini220-stration Regulations. Details of the U.S. Commercial Encryption Export 220-Controls can be found at the Bureau of Industry and Security web site. 220-All Oracle products are subject to U.S. Export Laws. Diversion contrary 220-to U.S. law is prohibited. ... 220220**************************************************************************** 220220
40
42
44
Values Files
res/values/strings.xml
Defines title, prompts, and button labels for all Activities in this section.
Used in both portrait and landscape mode.
res/values/colors.xml
Defines foreground color for some of the results
Used in both portrait and landscape mode.
res/values/dimens.xml
Gives font sizes.
Used in portrait mode.
res/values-land/dimens.xml
Gives font sizes.
45
46
Results
49
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Approach
Parse a URL into the host, port (80 if none) and URI Connect to host on port. Send request for URI plus Host request header (for servers with virtual hosting) Read status line and see if it is 2xx (good), 3xx (forwarded) or anything else (bad).
If forwarded, keep reading to find Location header
Note
51
Here we use no HTTP-specific classes. Next tutorial section covers HttpURLConnection and other HTTP-specific classes.
Response
HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: ... (Blank Line) <!DOCTYPE ...> <HTML> <HEAD>...</HEAD> <BODY> ... </BODY></HTML>
52
Response
HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: ...
53
57
59
Values Files
res/values/strings.xml
Defines title, prompts, and button labels for all Activities in this section.
Used in both portrait and landscape mode.
res/values/colors.xml
Defines foreground color for some of the results
Used in both portrait and landscape mode.
res/values/dimens.xml
Gives font sizes.
Used in portrait mode.
res/values-land/dimens.xml
Gives font sizes.
60
61
63
64
65
Helper Classes
StatusLineParser
Reads status line and breaks it into three parts: HTTP version, status code, and message
Also isGood (status code in the 200s), isForwarded (301/302) and isBad (anything else) methods
UrlParser
Breaks a URL like http://host:port/path into the host, port, and path parts. Uses 80 if no port specified. Note that the builtin URL class already does this. See next lecture. But Android has no builtin support for protocols other than HTTP, so learning to do it yourself is important.
66
Results
67
Wrap-Up
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, Servlets, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
More Reading
JavaDoc
Socket
http://developer.android.com/reference/java/net/Socket.html
Tutorial: Networking
http://download.oracle.com/javase/tutorial/networking/
Not Android specific, but still very good networking coverage
Chapters
Networking and Web Services
From Android in Action by Ableson et al
From The Busy Coders Guide to Android Development by Mark Murphy (http://commonsware.com/Android/)
Summary
Basics
Socket socket = new Socket(host, port); PrintWriter out = SocketUtils.getWriter(socket); BufferedReader in = SocketUtils.getReader(socket);
Slightly longer if you dont use SocketUtils Catch UnknownHostException and IOException
Questions?
JSF 2, PrimeFaces, Java 7, Ajax, jQuery, Hadoop, RESTful Web Services, Android, Spring, Hibernate, Servlets, JSP, GWT, and other Java EE training.
Developed and taught by well-known author and developer. At public venues or onsite at your location.