• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Presentation_1367055457962
 

Presentation_1367055457962

on

  • 268 views

 

Statistics

Views

Total Views
268
Views on SlideShare
268
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Most URLs can be broken into about five pieces, not all of which are necessarily present in any given URL. These are: There may also be a query string part which is used for CGI data. We’ll talk about that when we discuss CGIs.

Presentation_1367055457962 Presentation_1367055457962 Presentation Transcript

  • © 1999 Elliotte Rusty Harold 04/27/13URLs, InetAddresses, andURLConnectionsHigh Level Network ProgrammingElliotte Rusty Haroldelharo@metalab.unc.eduhttp://metalab.unc.edu/javafaq/slides/
  • © 1999 Elliotte Rusty Harold 04/27/13We will learn how Javahandles• Internet Addresses• URLs• CGI• URLConnection• Content and Protocol handlers
  • © 1999 Elliotte Rusty Harold 04/27/13I assume you• Understand basic Java syntax and I/O• Have a user’s view of the Internet• No prior network programmingexperience
  • © 1999 Elliotte Rusty Harold 04/27/13Applet Network SecurityRestrictions• Applets may:– send data to the code base– receive data from the code base• Applets may not:– send data to hosts other than the code base– receive data from hosts other than the codebase
  • © 1999 Elliotte Rusty Harold 04/27/13Some Background• Hosts• Internet Addresses• Ports• Protocols
  • © 1999 Elliotte Rusty Harold 04/27/13Hosts• Devices connected to the Internet arecalled hosts• Most hosts are computers, but hosts alsoinclude routers, printers, fax machines,soda machines, bat houses, etc.
  • © 1999 Elliotte Rusty Harold 04/27/13Internet addresses• Every host on the Internet is identified by aunique, four-byte Internet Protocol (IP)address.• This is written in dotted quad format like199.1.32.90 where each byte is an unsignedinteger between 0 and 255.• There are about four billion unique IPaddresses, but they aren’t very efficientlyallocated
  • © 1999 Elliotte Rusty Harold 04/27/13Domain Name System(DNS)• Numeric addresses are mapped to nameslike "www.blackstar.com" or"star.blackstar.com" by DNS.• Each site runs domain name serversoftware that translates names to IPaddresses and vice versa• DNS is a distributed system
  • © 1999 Elliotte Rusty Harold 04/27/13The InetAddress Class• The java.net.InetAddress classrepresents an IP address.• It converts numeric addresses to hostnames and host names to numericaddresses.• It is used by other network classes likeSocket and ServerSocket to identifyhosts
  • © 1999 Elliotte Rusty Harold 04/27/13Creating InetAddresses• There are no public InetAddress()constructors. Arbitrary addresses maynot be created.• All addresses that are created must bechecked with DNS
  • © 1999 Elliotte Rusty Harold 04/27/13The getByName() factorymethodpublic static InetAddress getByName(Stringhost) throws UnknownHostExceptionInetAddress utopia, duke;try {utopia = InetAddress.getByName("utopia.poly.edu");duke = InetAddress.getByName("128.238.2.92");}catch (UnknownHostException e) {System.err.println(e);}
  • © 1999 Elliotte Rusty Harold 04/27/13Other ways to createInetAddress objectspublic static InetAddress[] getAllByName(String host)throws UnknownHostExceptionpublic static InetAddress getLocalHost() throwsUnknownHostException
  • © 1999 Elliotte Rusty Harold 04/27/13Getter Methods• public boolean isMulticastAddress()• public String getHostName()• public byte[] getAddress()• public String getHostAddress()
  • © 1999 Elliotte Rusty Harold 04/27/13Utility Methods• public int hashCode()• public boolean equals(Object o)• public String toString()
  • © 1999 Elliotte Rusty Harold 04/27/13Ports• In general a host has only one Internetaddress• This address is subdivided into 65,536ports• Ports are logical abstractions that allowone host to communicate simultaneouslywith many other hosts• Many services run on well-known ports.For example, http tends to run on port 80
  • © 1999 Elliotte Rusty Harold 04/27/13Protocols• A protocol defines how two hosts talk toeach other.• The daytime protocol, RFC 867, specifiesan ASCII representation for the timethats legible to humans.• The time protocol, RFC 868, specifies abinary representation, for the time thatslegible to computers.• There are thousands of protocols,standard and non-standard
  • © 1999 Elliotte Rusty Harold 04/27/13IETF RFCs• Requests For Comment• Document how much of the Internetworks• Various status levels from obsolete torequired to informational• TCP/IP, telnet, SMTP, MIME, HTTP,and more• http://www.faqs.org/rfc/
  • © 1999 Elliotte Rusty Harold 04/27/13W3C Standards• IETF is based on “rough consensus andrunning code”• W3C tries to run ahead ofimplementation• IETF is an informal organization open toparticipation by anyone• W3C is a vendor consortium open only tocompanies
  • © 1999 Elliotte Rusty Harold 04/27/13W3C Standards• HTTP• HTML• XML• RDF• MathML• SMIL• P3P
  • © 1999 Elliotte Rusty Harold 04/27/13URLs• A URL, short for "Uniform ResourceLocator", is a way to unambiguouslyidentify the location of a resource on theInternet.
  • © 1999 Elliotte Rusty Harold 04/27/13Example URLshttp://java.sun.com/file:///Macintosh%20HD/Java/Docs/JDK%201.1.1%20docs/api/java.net.InetAddress.html#_top_http://www.macintouch.com:80/newsrecent.shtmlftp://ftp.info.apple.com/pub/mailto:elharo@metalab.unc.edutelnet://utopia.poly.eduftp://mp3:mp3@138.247.121.61:21000/c%3a/stuff/mp3/http://elharo@java.oreilly.com/http://metalab.unc.edu/nywc/comps.phtml?category=Choral+Works
  • © 1999 Elliotte Rusty Harold 04/27/13The Pieces of a URL• the protocol, aka scheme• the authority– user infouser namepassword– host name or address– port• the path, aka file• the ref, aka section or anchor• the query string
  • © 1999 Elliotte Rusty Harold 04/27/13The 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 canread data from a server– get content from the server as a Java object
  • © 1999 Elliotte Rusty Harold 04/27/13Content and ProtocolHandlers• Content and protocol handlers separate the databeing downloaded from the the protocol used todownload it.• The protocol handler negotiates with the serverand parses any headers. It gives the contenthandler only the actual data of the requestedresource.• The content handler translates those bytes into aJava object like an InputStream orImageProducer.
  • © 1999 Elliotte Rusty Harold 04/27/13Finding Protocol Handlers• When the virtual machine creates a URLobject, it looks for a protocol handlerthat understands the protocol part of theURL such as "http" or "mailto".• If no such handler is found, theconstructor throws aMalformedURLException.
  • © 1999 Elliotte Rusty Harold 04/27/13Supported Protocols• The exact protocols that Java supportsvary from implementation toimplementation though http and file aresupported pretty much everywhere.Suns JDK 1.1 understands ten:– file– ftp– gopher– http– mailto–appletresource–doc–netdoc–systemresource–verbatim
  • © 1999 Elliotte Rusty Harold 04/27/13URL Constructors• There are four (six in 1.2) constructors in thejava.net.URL class.public URL(String u) throws MalformedURLExceptionpublic URL(String protocol, String host, String file)throws MalformedURLExceptionpublic URL(String protocol, String host, int port,String file) throws MalformedURLExceptionpublic URL(URL context, String url) throwsMalformedURLExceptionpublic URL(String protocol, String host, int port,String file, URLStreamHandler handler) throwsMalformedURLExceptionpublic URL(URL context, String url, URLStreamHandlerhandler) throws MalformedURLException
  • © 1999 Elliotte Rusty Harold 04/27/13Constructing URL Objects• An absolute URL likehttp://www.poly.edu/fall97/grad.html#cstry {URL u = newURL("http://www.poly.edu/fall97/grad.html#cs");}catch (MalformedURLException e) {}
  • © 1999 Elliotte Rusty Harold 04/27/13Constructing URL Objects inPieces• You can also construct the URL bypassing its pieces to the constructor, likethis:URL u = null;try {u = new URL("http","www.poly.edu","/schedule/fall97/bgrad.html#cs");}catch (MalformedURLException e) {}
  • © 1999 Elliotte Rusty Harold 04/27/13Including the PortURL u = null;try {u = new URL("http","www.poly.edu", 8000,"/fall97/grad.html#cs");}catch (MalformedURLException e) {}
  • © 1999 Elliotte Rusty Harold 04/27/13Relative URLs• Many HTML files contain relative URLs.• Consider the pagehttp://metalab.unc.edu/javafaq/index.html• On this page a link to “books.html" refers tohttp://metalab.unc.edu/javafaq/books.html.
  • © 1999 Elliotte Rusty Harold 04/27/13Constructing Relative URLs• The fourth constructor creates URLsrelative to a given URL. For example,try {URL u1 = newURL("http://metalab.unc.edu/index.html");URL u2 = new URL(u1, ”books.html");}catch (MalformedURLException e) {}• This is particularly useful when parsingHTML.
  • © 1999 Elliotte Rusty Harold 04/27/13Parsing URLs• The java.net.URL class has fivemethods to split a URL into itscomponent parts. These are:public String getProtocol()public String getHost()public int getPort()public String getFile()public String getRef()
  • © 1999 Elliotte Rusty Harold 04/27/13For example,try {URL u = newURL("http://www.poly.edu/fall97/grad.html#cs ");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());System.out.println("The anchor is " +u.getRef());}catch (MalformedURLException e) { }
  • © 1999 Elliotte Rusty Harold 04/27/13Parsing URLs• JDK 1.3 adds three more:public String getAuthority()public String getUserInfo()public String getQuery()
  • © 1999 Elliotte Rusty Harold 04/27/13Missing Pieces• If a port is not explicitly specified in the URLits set to -1. This means the default port is tobe used.• If the ref doesnt exist, its just null, so watchout for NullPointerExceptions. Betteryet, test to see that its non-null before usingit.• If the file is left off completely, e.g.http://java.sun.com, then its set to "/".
  • © 1999 Elliotte Rusty Harold 04/27/13Reading Data from a URL• The openStream() method connects to theserver specified in the URL and returns anInputStream object fed by the data from thatconnection.public final InputStream openStream() throwsIOException• Any headers that precede the actual data arestripped off before the stream is opened.• Network connections are less reliable and slowerthan files. Buffer with a BufferedReader or aBufferedInputStream.
  • © 1999 Elliotte Rusty Harold 04/27/13Webcatimport java.net.*;import java.io.*;public class Webcat {public static void main(String[] args) {for (int i = 0; i < args.length; i++) {try {URL u = new URL(args[i]);InputStream in = u.openStream();InputStreamReader isr = new InputStreamReader(in);BufferedReader br = new BufferedReader(isr);String theLine;while ((theLine = br.readLine()) != null) {System.out.println(theLine);}} catch (IOException e) { System.err.println(e);}}}}
  • © 1999 Elliotte Rusty Harold 04/27/13The Bug in readLine()• What readLine() does:– Sees a carriage return, waits to see if nextcharacter is a line feed before returning• What readLine() should do:– Sees a carriage return, return, throw awaynext character if its a linefeed
  • © 1999 Elliotte Rusty Harold 04/27/13Webcatimport java.net.*;import java.io.*;public class Webcat {public static void main(String[] args) {for (int i = 0; i < args.length; i++) {try {URL u = new URL(args[i]);InputStream in = u.openStream();InputStreamReader isr = new InputStreamReader(in);char c;while ((c = br.read()) != -1) {System.out.print(c);}} catch (IOException e) { System.err.println(e);}}}}
  • © 1999 Elliotte Rusty Harold 04/27/13CGI• Common Gateway Interface• A lot is written about writing server sideCGI. I’m going to show you client sideCGI.• We’ll need to explore HTTP a littledeeper to do this
  • © 1999 Elliotte Rusty Harold 04/27/13Normal web surfing usesthese two steps:– The browser requests a page– The server sends the page• Data flows primarily from the server tothe client.
  • © 1999 Elliotte Rusty Harold 04/27/13Forms• There are times when the server needs toget data from the client rather than theother way around. The common way todo this is with a form like this one:
  • © 1999 Elliotte Rusty Harold 04/27/13CGI• The user types the requested data into theform and hits the submit button.• The client browser then sends the data to theserver using the Common Gateway Interface,CGI for short.• CGI uses the HTTP protocol to transmit thedata, either as part of the query string or asseparate data following the MIME header.
  • © 1999 Elliotte Rusty Harold 04/27/13GET and POST• When the data is sent as a query stringincluded with the file request, this iscalled CGI GET.• When the data is sent as data attached tothe request following the MIME header,this is called CGI POST
  • © 1999 Elliotte Rusty Harold 04/27/13HTTP• Web browsers communicate with web serversthrough a standard protocol known as HTTP,an acronym for HyperText TransferProtocol.• This protocol defines– how a browser requests a file from a web server– how a browser sends additional data along withthe request (e.g. the data formats it can accept),– how the server sends data back to the client– response codes
  • © 1999 Elliotte Rusty Harold 04/27/13A Typical HTTP Connection– Client opens a socket to port 80 on the server.– Client sends a GET request including the nameand path of the file it wants and the version ofthe 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.
  • © 1999 Elliotte Rusty Harold 04/27/13What the client sends to theserverGET /javafaq/images/cup.gifConnection: Keep-AliveUser-Agent: Mozilla/3.01 (Macintosh; I; PPC)Host: www.oreilly.com:80Accept: image/gif, image/x-xbitmap, image/jpeg, */*
  • © 1999 Elliotte Rusty Harold 04/27/13MIME• MIME is an acronym for "MultipurposeInternet Mail Extensions".• an Internet standard defined in RFCs2045 through 2049• originally intended for use with emailmessages, but has been been adopted foruse in HTTP.
  • © 1999 Elliotte Rusty Harold 04/27/13Browser Request MIMEHeader• When the browser sends a request to aweb server, it also sends a MIME header.• MIME headers contain name-valuepairs, essentially a name followed by acolon and a space, followed by a value.Connection: Keep-AliveUser-Agent: Mozilla/3.01 (Macintosh; I; PPC)Host: www.digitalthink.com:80Accept: image/gif, image/x-xbitmap,image/jpeg, image/pjpeg, */*
  • © 1999 Elliotte Rusty Harold 04/27/13Server Response MIMEHeader• When a web server responds to a webbrowser it sends a MIME header alongwith the response that looks somethinglike this:Server: Netscape-Enterprise/2.01Date: Sat, 02 Aug 1997 07:52:46 GMTAccept-ranges: bytesLast-modified: Tue, 29 Jul 199715:06:46 GMTContent-length: 2810Content-type: text/html
  • © 1999 Elliotte Rusty Harold 04/27/13Query Strings• CGI GET data is sent in URL encodedquery strings• a query string is a set of name=valuepairs separated by ampersandsAuthor=Sadie, Julie&Title=WomenComposers• separated from rest of URL by a questionmark
  • © 1999 Elliotte Rusty Harold 04/27/13URL Encoding• Alphanumeric ASCII characters (a-z, A-Z,and 0-9) and the $-_.!*(), punctuationsymbols are left unchanged.• The space character is converted into a plussign (+).• Other characters (e.g. &, =, ^, #, %, ^, {,and so on) are translated into a percentsign followed by the two hexadecimal digitscorresponding to their numeric value.
  • © 1999 Elliotte Rusty Harold 04/27/13For example,• The comma is ASCII character 44(decimal) or 2C (hex). Therefore if thecomma appears as part of a URL it isencoded as %2C.• The query string "Author=Sadie,Julie&Title=Women Composers" isencoded as:Author=Sadie%2C+Julie&Title=Women+Composers
  • © 1999 Elliotte Rusty Harold 04/27/13The URLEncoder class• The java.net.URLEncoder classcontains a single static method whichencodes strings in x-www-form-url-encoded formatURLEncoder.encode(String s)
  • © 1999 Elliotte Rusty Harold 04/27/13For 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
  • © 1999 Elliotte Rusty Harold 04/27/13String eqs = "Author=" +URLEncoder.encode("Sadie, Julie");eqs += "&";eqs += "Title=";eqs += URLEncoder.encode("WomenComposers");• This prints the properly encoded querystring:Author=Sadie%2c+Julie&Title=Women+Composers
  • © 1999 Elliotte Rusty Harold 04/27/13The URLDecoder class• In Java 1.2 thejava.net.URLDecoder class containsa single static method which decodesstrings in x-www-form-url-encodedformatURLEncoder.decode(String s)
  • © 1999 Elliotte Rusty Harold 04/27/13GET URLsString eqs ="Author=" + URLEncoder.encode("Sadie, Julie");eqs += "&";eqs += "Title=";eqs += URLEncoder.encode("Women Composers");try {URL u = newURL("http://www.superbooks.com/search.cgi?" + eqs);InputStream in = u.openStream();//...}catch (IOException e) { //...
  • © 1999 Elliotte Rusty Harold 04/27/13URLConnections• The java.net.URLConnection classis an abstract class that handlescommunication with different kinds ofservers like ftp servers and web servers.• Protocol specific subclasses ofURLConnection handle different kindsof servers.• By default, connections to HTTP URLsuse the GET method.
  • © 1999 Elliotte Rusty Harold 04/27/13URLConnections vs. URLs• Can send output as well as read input• Can post data to CGIs• Can read headers from a connection
  • © 1999 Elliotte Rusty Harold 04/27/13URLConnection five steps:1. The URL is constructed.2. The URL’s openConnection() methodcreates the URLConnection object.3. The parameters for the connection and therequest properties that the client sends to theserver are set up.4. The connect() method makes the connectionto the server. (optional)5. The response header information is read usinggetHeaderField().
  • © 1999 Elliotte Rusty Harold 04/27/13I/O Across aURLConnection• Data may be read from the connection inone of two ways– raw by using the input stream returned bygetInputStream()– through a content handler withgetContent().• Data can be sent to the server using theoutput stream provided bygetOutputStream().
  • © 1999 Elliotte Rusty Harold 04/27/13For example,try {URL u = newURL("http://www.sd99.com/");URLConnection uc =u.openConnection();uc.connect();InputStream in =uc.getInputStream();// read the data...}catch (IOException e) { //...
  • © 1999 Elliotte Rusty Harold 04/27/13Reading Header Data• The getHeaderField(String name)method returns the string value of a namedheader field.• Names are case-insensitive.• If the requested field is not present, null isreturned.String lm = uc.getHeaderField("Last-modified");
  • © 1999 Elliotte Rusty Harold 04/27/13getHeaderFieldKey()• The keys of the header fields are returned bythe getHeaderFieldKey(int n)method.• The first field is 1.• If a numbered key is not found, null isreturned.• You can use this in combination withgetHeaderField() to loop through thecomplete header
  • © 1999 Elliotte Rusty Harold 04/27/13For exampleString key = null;for (int i=1; (key =uc.getHeaderFieldKey(i))!=null);i++) {System.out.println(key + ": " +uc.getHeaderField(key));}
  • © 1999 Elliotte Rusty Harold 04/27/13getHeaderFieldInt() andgetHeaderFieldDate()• These are utility methods that read a namedheader and convert its value into an int and along respectively.public int getHeaderFieldInt(String name, int default)public long getHeaderFieldDate(String name, longdefault)
  • © 1999 Elliotte Rusty Harold 04/27/13• The long returned bygetHeaderFieldDate() can be convertedinto a Date object using a Date() constructorlike this:String s = uc.getHeaderFieldDate("Last-modified", 0);Date lm = new Date(s);
  • © 1999 Elliotte Rusty Harold 04/27/13Six Convenience Methods• These return the values of sixparticularly common header fields:public int getContentLength()public String getContentType()public String getContentEncoding()public long getExpiration()public long getDate()public long getLastModified()
  • © 1999 Elliotte Rusty Harold 04/27/13try {URL u = new URL("http://www.sdexpo.com/");URLConnection uc = u.openConnection();uc.connect();String key=null;for (int n = 1;(key=uc.getHeaderFieldKey(n)) != null;n++) {System.out.println(key + ": " +uc.getHeaderField(key));}}catch (IOException e) {System.err.println(e);}
  • © 1999 Elliotte Rusty Harold 04/27/13Writing data to aURLConnection• Similar to reading data from a URLConnection.• First inform the URLConnection that you plan touse it for output• Before getting the connections input stream, getthe connections output stream and write to it.• Commonly used to talk to CGIs that use thePOST method
  • © 1999 Elliotte Rusty Harold 04/27/13Eight Steps:1.Construct the URL.2.Call the URL’s openConnection()method to create the URLConnection object.3.Pass true to the URLConnection’ssetDoOutput() method4.Create the data you want to send, preferablyas a byte array.
  • © 1999 Elliotte Rusty Harold 04/27/135.Call getOutputStream() to get anoutput stream object.6.Write the byte array calculated in step 5onto the stream.7.Close the output stream.8.Call getInputStream() to get aninput stream object. Read from it asusual.
  • © 1999 Elliotte Rusty Harold 04/27/13POST CGIs• A typical POST request to a CGI looks likethis:POST /cgi-bin/booksearch.pl HTTP/1.0Referer:http://www.macfaq.com/sampleform.htmlUser-Agent: Mozilla/3.01 (Macintosh; I;PPC)Content-length: 60Content-type: text/x-www-form-urlencodedHost: utopia.poly.edu:56435username=Sadie%2C+Julie&realname=Women+Composers
  • © 1999 Elliotte Rusty Harold 04/27/13A POST request includes• the POST line• a MIME header which must include– content type– content length• a blank line that signals the end of theMIME header• the actual data of the form, encoded in x-www-form-urlencoded format.
  • © 1999 Elliotte Rusty Harold 04/27/13• A URLConnection for an http URL willset up the request line and the MIMEheader for you as long as you set itsdoOutput field to true by invokingsetDoOutput(true).• If you also want to read from theconnection, you should set doInput totrue with setDoInput(true) too.
  • © 1999 Elliotte Rusty Harold 04/27/13For example,URLConnection uc =u.openConnection();uc.setDoOutput(true);uc.setDoInput(true);
  • © 1999 Elliotte Rusty Harold 04/27/13• The request line and MIME header aresent as soon as the URLConnectionconnects. Then getOutputStream()returns an output stream on which youcan write the x-www-form-urlencodedname-value pairs.
  • © 1999 Elliotte Rusty Harold 04/27/13HttpURLConnection• java.net.HttpURLConnection is anabstract subclass of URLConnectionthat provides some additional methodsspecific to the HTTP protocol.• URL connection objects that arereturned by an http URL will beinstances ofjava.net.HttpURLConnection.
  • © 1999 Elliotte Rusty Harold 04/27/13Recall• a typical HTTP response from a webserver begins like this:HTTP/1.0 200 OKServer: Netscape-Enterprise/2.01Date: Sat, 02 Aug 1997 07:52:46 GMTAccept-ranges: bytesLast-modified: Tue, 29 Jul 199715:06:46 GMTContent-length: 2810Content-type: text/html
  • © 1999 Elliotte Rusty Harold 04/27/13Response Codes• The getHeaderField() andgetHeaderFieldKey() dont return theHTTP response code• After youve connected, you can retrieve thenumeric response code--200 in the aboveexample--with the getResponseCode()method and the message associated with it--OK in the above example--with thegetResponseMessage() method.
  • © 1999 Elliotte Rusty Harold 04/27/13HTTP Protocols• Java 1.0 only supports GET and POSTrequests to HTTP servers• Java 1.1/1.2 supports GET, POST, HEAD,OPTIONS, PUT, DELETE, and TRACE.• The protocol is chosen with thesetRequestMethod(String method)method.• A java.net.ProtocolException, asubclass of IOException, is thrown if anunknown protocol is specified.
  • © 1999 Elliotte Rusty Harold 04/27/13getRequestMethod()• The getRequestMethod() methodreturns the string form of the requestmethod currently set for theURLConnection. GET is the defaultmethod.
  • © 1999 Elliotte Rusty Harold 04/27/13disconnect()• The disconnect() method of theHttpURLConnection class closes theconnection to the web server.• Needed for HTTP/1.1 Keep-alive
  • © 1999 Elliotte Rusty Harold 04/27/13For example,try {URL u = newURL("http://www.amnesty.org/");HttpURLConnection huc =(HttpURLConnection)u.openConnection();huc.setRequestMethod("PUT");huc.connect();OutputStream os =huc.getOutputStream();int code = huc.getResponseCode();if (code >= 200 && < 300) {// put the data...}huc.disconnect();}catch (IOException e) { //...
  • © 1999 Elliotte Rusty Harold 04/27/13usingProxy• The boolean usingProxy() methodreturns true if web connections are beingfunneled through a proxy server, false iftheyre not.
  • © 1999 Elliotte Rusty Harold 04/27/13Redirect Instructions• Most web servers can be configured toautomatically redirect browsers to thenew location of a page thats moved.• To redirect browsers, a server sends a300 level response and a Location headerthat specifies the new location of therequested page.
  • © 1999 Elliotte Rusty Harold 04/27/13GET /~elharo/macfaq/index.html HTTP/1.0HTTP/1.1 302 Moved TemporarilyDate: Mon, 04 Aug 1997 14:21:27 GMTServer: Apache/1.2b7Location: http://www.macfaq.com/macfaq/index.htmlConnection: closeContent-type: text/html<HTML><HEAD><TITLE>302 Moved Temporarily</TITLE></HEAD><BODY><H1>Moved Temporarily</H1>The document has moved <AHREF="http://www.macfaq.com/macfaq/index.html">here</A>.<P></BODY></HTML>
  • © 1999 Elliotte Rusty Harold 04/27/13• HTML is returned for browsers thatdont understand redirects, but mostmodern browsers do not display this andjump straight to the page specified in theLocation header instead.• Because redirects can change the sitewhich a user is connecting without theirknowledge so redirects are notarbitrarily followed by URLConnections.
  • © 1999 Elliotte Rusty Harold 04/27/13Following RedirectsHttpURLConnection.setFollowRedirects(true) method says that connections will followredirect instructions from the web server.Untrusted applets are not allowed to set this.HttpURLConnection.getFollowRedirects() returns true if redirect requests are honored,false if theyre not.
  • © 1999 Elliotte Rusty Harold 04/27/13To Learn More• Java Network Programming– O’Reilly & Associates, 1997– ISBN 1-56592-227-1• Java I/O– O’Reilly & Associates, 1999– ISBN 1-56592-485-1• Web Client Programming with Java– http://www.digitalthink.com/catalog/cs/cs308/index.html
  • © 1999 Elliotte Rusty Harold 04/27/13Questions?