prepared by e. musa alyaman1 urls, inetaddresses, and urlconnections chapter 9
Post on 19-Dec-2015
215 views
TRANSCRIPT
Prepared By E. Musa Alyaman1
URLs, InetAddresses, and URLConnections
Chapter 9
Prepared By E. Musa Alyaman2
We will learn how Java handles
• 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]://utopia.poly.edu
Prepared By E. Musa Alyaman4
The Pieces of a URL
• the protocol.
• the authority– ://– host name or address– port
• the path
Prepared By E. Musa Alyaman5
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
Prepared By E. Musa Alyaman6
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.
Prepared By E. Musa Alyaman7
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.
Prepared By E. Musa Alyaman8
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
Prepared By E. Musa Alyaman9
Constructing URL Objects
• An absolute URL like http://www.poly.edu/fall97/grad.htmltry { URL u = newURL("http://www.poly.edu/fall97/grad.html");}catch (MalformedURLException e) {}
Prepared By E. Musa Alyaman10
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) {}
Prepared By E. Musa Alyaman11
Including the Port
URL u = null;
try {
u = new URL("http", "www.poly.edu", 8000, "/fall97/grad.html");
}
catch (MalformedURLException e) {}
Prepared By E. Musa Alyaman12
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.
Prepared By E. Musa Alyaman13
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) {}
Prepared By E. Musa Alyaman14
Parsing URLs
• The java.net.URL class has five methods to split a URL into its component parts. These are: public String getProtocol() public String getHost() public int getPort() public String getFile()
Prepared By E. Musa Alyaman15
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) { }
Prepared By E. Musa Alyaman16
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 "/".
Prepared By E. Musa Alyaman17
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.
Prepared By E. Musa Alyaman18
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.
Prepared By E. Musa Alyaman19
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:
Prepared By E. Musa Alyaman20
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.
Prepared By E. Musa Alyaman21
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.
Prepared By E. Musa Alyaman22
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
Prepared By E. Musa Alyaman23
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
Prepared By E. Musa Alyaman24
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.
Prepared By E. Musa Alyaman25
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.
Prepared By E. Musa Alyaman26
The URLEncoder class
• The java.net.URLEncoder class contains a single static method which encodes strings in x-www-form-url-encoded formatURLEncoder.encode(String s)
Prepared By E. Musa Alyaman27
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+Composers
Prepared By E. Musa Alyaman28
The URLDecoder class
• In Java 1.2 the java.net.URLDecoder class contains a single static method which decodes strings in x-www-form-url-encoded formatURLEncoder.decode(String s)
Prepared By E. Musa Alyaman29
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.
Prepared By E. Musa Alyaman30
URLConnections vs. URLs
• Can send output as well as read input
• Can post data to CGIs
• Can read headers from a connection
Prepared By E. Musa Alyaman31
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().
Prepared By E. Musa Alyaman32
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().
Prepared By E. Musa Alyaman33
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) { //...
Prepared By E. Musa Alyaman34
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 usingByteArrayInputStream and ByteArrayOutputStream
• How to listen for UDP packets• How to send UDP packets• How to create a UDP server and a UDP client