Data Streams

Download Report

Transcript Data Streams

Chapter 9
URLs, InetAddresses, and
URLConnections
1
Prepared By E. Musa Alyaman
We will learn how Java handles
•
•
•
•
2
URLs
CGI
URLConnection
Content and Protocol handlers
Prepared By E. Musa Alyaman
URLs
• A URL, short for "Uniform Resource
Locator", is a way to identify the location of
a resource on the Internet.
• Examples
http://java.sun.com/
ftp://ftp.info.apple.com/pub/
mailto:[email protected]
telnet://utopia.poly.edu
The Pieces of a URL
• the protocol.
• the authority
– ://
– host name or address
– port
• the path
4
Prepared By E. Musa Alyaman
The java.net.URL class
• A URL object represents a URL.
• The URL class contains methods to
– create new URLs
– parse the different parts of a URL
– get an input stream from a URL so you can
read data from a server
– get content from the server as a Java object
5
Prepared By E. Musa Alyaman
Content and Protocol Handlers
• Content and protocol handlers separate the
data being downloaded from the the protocol
used to download it.
• The protocol handler negotiates with the server
and parses any headers. It gives the content
handler only the actual data of the requested
resource.
• The content handler translates those bytes into
a Java object like an InputStream.
6
Prepared By E. Musa Alyaman
Finding Protocol Handlers
• When the virtual machine creates a URL
object, it looks for a protocol handler that
understands the protocol part of the URL
such as "http".
• If no such handler is found, the constructor
throws a MalformedURLException.
7
Prepared By E. Musa Alyaman
URL Constructors
• There are four constructors in the
java.net.URL class.
public URL(String u) throws
MalformedURLException
public URL(String protocol, String host,
String file) throws MalformedURLException
public URL(String protocol, String host, int
port, String file) throws
MalformedURLException
public URL(URL context, String url) throws
MalformedURLException
8
Prepared By E. Musa Alyaman
Constructing URL Objects
• An absolute URL like
http://www.poly.edu/fall97/grad.html
try {
URL u = new
URL("http://www.poly.edu/fall97/grad.html");
}
catch (MalformedURLException e) {}
9
Prepared By E. Musa Alyaman
Constructing URL Objects in
Pieces
You can also construct the URL by passing
its pieces to the constructor, like this:
URL u = null;
try {
u = new URL("http", "www.poly.edu",
"/schedule/fall97/bgrad.html");
}
catch (MalformedURLException e) {}
10
Prepared By E. Musa Alyaman
Including the Port
URL u = null;
try {
u = new URL("http", "www.poly.edu", 8000,
"/fall97/grad.html");
}
catch (MalformedURLException e) {}
11
Prepared By E. Musa Alyaman
Relative URLs
• Many HTML files contain relative URLs.
• Consider the page
http://metalab.unc.edu/javafaq/index.html
• On this page a link to “books.html" refers to
http://metalab.unc.edu/javafaq/books.html.
12
Prepared By E. Musa Alyaman
Constructing Relative URLs
• The fourth constructor creates URLs
relative to a given URL. For example,
try {
URL u1 = new
URL("http://metalab.unc.edu/index.html"
);
URL u2 = new URL(u1, ”books.html");
}
catch (MalformedURLException e) {}
13
Prepared By E. Musa Alyaman
Parsing URLs
• The java.net.URL class has five
methods to split a URL into its component
parts. These are:
public
public
public
public
14
String
String
int
String
getProtocol()
getHost()
getPort()
getFile()
Prepared By E. Musa Alyaman
For example,
try {
URL u = new URL("http://www.poly.edu/fall97/grad.html ");
System.out.println("The protocol is " + u.getProtocol());
System.out.println("The host is " + u.getHost());
System.out.println("The port is " + u.getPort());
System.out.println("The file is " + u.getFile());
}
catch (MalformedURLException e) { }
15
Prepared By E. Musa Alyaman
Missing Pieces
• If a port is not explicitly specified in the URL
it's set to -1. This means the default port is
to be used.
• If the file is left off completely, e.g.
http://java.sun.com, then it's set to "/".
16
Prepared By E. Musa Alyaman
Reading Data from a URL
• The openStream() method connects to the server specified in
the URL and returns an InputStream object fed by the data
from that connection.
• public final InputStream openStream() throws
IOException
• Any headers that precede the actual data are stripped off
before the stream is opened.
• Network connections are less reliable and slower than files.
Buffer with a BufferedReader or a BufferedInputStream.
17
Prepared By E. Musa Alyaman
Common Gateway Interface (CGI)
• Normal web uses these two steps:
– The browser requests a page
– The server sends the page
• Data flows primarily from the server to the
client.
18
Prepared By E. Musa Alyaman
Forms
• There are times when the server needs to
get data from the client rather than the
other way around. The common way to do
this is with a form like this one:
19
Prepared By E. Musa Alyaman
CGI
• The user types the requested data into the
form and hits the submit button.
• The client browser then sends the data to
the server using the Common Gateway
Interface, CGI for short.
• CGI uses the HTTP protocol to transmit the
data, either as part of the query string or as
separate data following the MIME header.
20
Prepared By E. Musa Alyaman
MIME
• MIME is stands for "Multipurpose Internet
Mail Extensions".
• an Internet standard defined in RFCs 2045
through 2049
• originally intended for use with email
messages, but has been been adopted for
use in HTTP.
21
Prepared By E. Musa Alyaman
GET and POST
• When the data is sent as a query string
included with the file request, this is called
CGI GET.
• When the data is sent as data attached to
the request following the MIME header,
this is called CGI POST
22
Prepared By E. Musa Alyaman
HTTP
• Web browsers communicate with web
servers through a standard protocol known
as HTTP, ( HyperText Transfer Protocol).
• This protocol defines
– how a browser requests a file from a web server
– how a browser sends additional data along with
the request (e.g. the data formats it can accept),
– how the server sends data back to the client
23
Prepared By E. Musa Alyaman
A Typical HTTP Connection
– Client opens a socket to port 80 on the
server.
– Client sends a GET request including the
name and path of the file it wants and the
version of the HTTP protocol it supports.
– The client sends a MIME header.
– The client sends a blank line.
– The server sends a MIME header
– The server sends the data in the file.
– The server closes the connection.
24
Prepared By E. Musa Alyaman
URL Encoding
• Alphanumeric ASCII characters (a-z, A-Z,
and 0-9) and the $-_.!*'(), punctuation
symbols are left unchanged.
• The space character is converted into a
plus sign (+).
• Other characters (e.g. &, =, ^, #, %, ^, {,
and so on) are translated into a percent
sign followed by the two hexadecimal
digits corresponding to their numeric
value.
25
Prepared By E. Musa Alyaman
The URLEncoder class
• The java.net.URLEncoder class
contains a single static method which
encodes strings in x-www-form-urlencoded format
URLEncoder.encode(String s)
26
Prepared By E. Musa Alyaman
For example
String qs = "Author=Sadie, Julie&Title=Women Composers";
String eqs = URLEncoder.encode(qs);
System.out.println(eqs);
• This prints:
• Author%3dSadie%2c+Julie%26Title%3dWomen+Comp
osers
27
Prepared By E. Musa Alyaman
The URLDecoder class
• In Java 1.2 the java.net.URLDecoder
class contains a single static method
which decodes strings in x-www-form-urlencoded format
URLEncoder.decode(String s)
28
Prepared By E. Musa Alyaman
URLConnections
• The java.net.URLConnection
class is a class that handles
communication with different kinds of
servers like ftp servers and web
servers.
• Protocol specific subclasses of
URLConnection handle different kinds
of servers.
• By default, connections to HTTP URLs
use the GET method.
29
Prepared By E. Musa Alyaman
URLConnections vs. URLs
• Can send output as well as read input
• Can post data to CGIs
• Can read headers from a connection
30
Prepared By E. Musa Alyaman
URLConnection five steps:
1. The URL is constructed.
2. The URL’s openConnection() method
creates the URLConnection object.
3. The parameters for the connection and the
request properties that the client sends to the
server are set up.
4. The connect() method makes the
connection to the server.
5. The response header information is read using
getHeaderField().
31
Prepared By E. Musa Alyaman
I/O Across a URLConnection
• Data may be read from the connection
in one of two ways
– raw by using the input stream returned by
getInputStream()
– through a content handler with
getContent().
• Data can be sent to the server using
the output stream provided by
getOutputStream().
32
Prepared By E. Musa Alyaman
For example,
try {
URL u = new URL("http://www.sd99.com/");
URLConnection uc = u.openConnection();
uc.connect();
InputStream in = uc.getInputStream();
// read the data...
}
catch (IOException e) { //...
33
Prepared By E. Musa Alyaman
Chapter Highlights
In this chapter, you have learned:
• How to bind to a local port using DatagramSocket
• How to create a DatagramPacket
• How to read from, and write to, a
DatagramPacket using
ByteArrayInputStream and
ByteArrayOutputStream
• How to listen for UDP packets
• How to send UDP packets
• How to create a UDP server and a UDP client
34
Prepared By E. Musa Alyaman