Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • 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

    1. 1. © 1999 Elliotte Rusty Harold 04/27/13URLs, InetAddresses, andURLConnectionsHigh Level Network ProgrammingElliotte Rusty Haroldelharo@metalab.unc.edu
    2. 2. © 1999 Elliotte Rusty Harold 04/27/13We will learn how Javahandles• Internet Addresses• URLs• CGI• URLConnection• Content and Protocol handlers
    3. 3. © 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
    4. 4. © 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
    5. 5. © 1999 Elliotte Rusty Harold 04/27/13Some Background• Hosts• Internet Addresses• Ports• Protocols
    6. 6. © 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.
    7. 7. © 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
    8. 8. © 1999 Elliotte Rusty Harold 04/27/13Domain Name System(DNS)• Numeric addresses are mapped to nameslike "" or"" by DNS.• Each site runs domain name serversoftware that translates names to IPaddresses and vice versa• DNS is a distributed system
    9. 9. © 1999 Elliotte Rusty Harold 04/27/13The InetAddress Class• The 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
    10. 10. © 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
    11. 11. © 1999 Elliotte Rusty Harold 04/27/13The getByName() factorymethodpublic static InetAddress getByName(Stringhost) throws UnknownHostExceptionInetAddress utopia, duke;try {utopia = InetAddress.getByName("");duke = InetAddress.getByName("");}catch (UnknownHostException e) {System.err.println(e);}
    12. 12. © 1999 Elliotte Rusty Harold 04/27/13Other ways to createInetAddress objectspublic static InetAddress[] getAllByName(String host)throws UnknownHostExceptionpublic static InetAddress getLocalHost() throwsUnknownHostException
    13. 13. © 1999 Elliotte Rusty Harold 04/27/13Getter Methods• public boolean isMulticastAddress()• public String getHostName()• public byte[] getAddress()• public String getHostAddress()
    14. 14. © 1999 Elliotte Rusty Harold 04/27/13Utility Methods• public int hashCode()• public boolean equals(Object o)• public String toString()
    15. 15. © 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
    16. 16. © 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
    17. 17. © 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•
    18. 18. © 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
    19. 19. © 1999 Elliotte Rusty Harold 04/27/13W3C Standards• HTTP• HTML• XML• RDF• MathML• SMIL• P3P
    20. 20. © 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.
    21. 21. © 1999 Elliotte Rusty Harold 04/27/13Example URLs
    22. 22. © 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
    23. 23. © 1999 Elliotte Rusty Harold 04/27/13The 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
    24. 24. © 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.
    25. 25. © 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.
    26. 26. © 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
    27. 27. © 1999 Elliotte Rusty Harold 04/27/13URL Constructors• There are four (six in 1.2) constructors in 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
    28. 28. © 1999 Elliotte Rusty Harold 04/27/13Constructing URL Objects• An absolute URL like {URL u = newURL("");}catch (MalformedURLException e) {}
    29. 29. © 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","","/schedule/fall97/bgrad.html#cs");}catch (MalformedURLException e) {}
    30. 30. © 1999 Elliotte Rusty Harold 04/27/13Including the PortURL u = null;try {u = new URL("http","", 8000,"/fall97/grad.html#cs");}catch (MalformedURLException e) {}
    31. 31. © 1999 Elliotte Rusty Harold 04/27/13Relative URLs• Many HTML files contain relative URLs.• Consider the page• On this page a link to “books.html" refers to
    32. 32. © 1999 Elliotte Rusty Harold 04/27/13Constructing Relative URLs• The fourth constructor creates URLsrelative to a given URL. For example,try {URL u1 = newURL("");URL u2 = new URL(u1, ”books.html");}catch (MalformedURLException e) {}• This is particularly useful when parsingHTML.
    33. 33. © 1999 Elliotte Rusty Harold 04/27/13Parsing URLs• The 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()
    34. 34. © 1999 Elliotte Rusty Harold 04/27/13For example,try {URL u = newURL(" ");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) { }
    35. 35. © 1999 Elliotte Rusty Harold 04/27/13Parsing URLs• JDK 1.3 adds three more:public String getAuthority()public String getUserInfo()public String getQuery()
    36. 36. © 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., then its set to "/".
    37. 37. © 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.
    38. 38. © 1999 Elliotte Rusty Harold 04/27/13Webcatimport*;import*;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);}}}}
    39. 39. © 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
    40. 40. © 1999 Elliotte Rusty Harold 04/27/13Webcatimport*;import*;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 = != -1) {System.out.print(c);}} catch (IOException e) { System.err.println(e);}}}}
    41. 41. © 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
    42. 42. © 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.
    43. 43. © 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:
    44. 44. © 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.
    45. 45. © 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
    46. 46. © 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
    47. 47. © 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.
    48. 48. © 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: image/gif, image/x-xbitmap, image/jpeg, */*
    49. 49. © 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.
    50. 50. © 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: image/gif, image/x-xbitmap,image/jpeg, image/pjpeg, */*
    51. 51. © 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
    52. 52. © 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
    53. 53. © 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.
    54. 54. © 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
    55. 55. © 1999 Elliotte Rusty Harold 04/27/13The URLEncoder class• The classcontains a single static method whichencodes strings in x-www-form-url-encoded formatURLEncoder.encode(String s)
    56. 56. © 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
    57. 57. © 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
    58. 58. © 1999 Elliotte Rusty Harold 04/27/13The URLDecoder class• In Java 1.2 class containsa single static method which decodesstrings in x-www-form-url-encodedformatURLEncoder.decode(String s)
    59. 59. © 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("" + eqs);InputStream in = u.openStream();//...}catch (IOException e) { //...
    60. 60. © 1999 Elliotte Rusty Harold 04/27/13URLConnections• The 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.
    61. 61. © 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
    62. 62. © 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().
    63. 63. © 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().
    64. 64. © 1999 Elliotte Rusty Harold 04/27/13For example,try {URL u = newURL("");URLConnection uc =u.openConnection();uc.connect();InputStream in =uc.getInputStream();// read the data...}catch (IOException e) { //...
    65. 65. © 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");
    66. 66. © 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
    67. 67. © 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));}
    68. 68. © 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)
    69. 69. © 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);
    70. 70. © 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()
    71. 71. © 1999 Elliotte Rusty Harold 04/27/13try {URL u = new URL("");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);}
    72. 72. © 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
    73. 73. © 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.
    74. 74. © 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.
    75. 75. © 1999 Elliotte Rusty Harold 04/27/13POST CGIs• A typical POST request to a CGI looks likethis:POST /cgi-bin/ HTTP/1.0Referer: Mozilla/3.01 (Macintosh; I;PPC)Content-length: 60Content-type: text/x-www-form-urlencodedHost:
    76. 76. © 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.
    77. 77. © 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.
    78. 78. © 1999 Elliotte Rusty Harold 04/27/13For example,URLConnection uc =u.openConnection();uc.setDoOutput(true);uc.setDoInput(true);
    79. 79. © 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.
    80. 80. © 1999 Elliotte Rusty Harold 04/27/13HttpURLConnection• is anabstract subclass of URLConnectionthat provides some additional methodsspecific to the HTTP protocol.• URL connection objects that arereturned by an http URL will beinstances
    81. 81. © 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
    82. 82. © 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.
    83. 83. © 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, asubclass of IOException, is thrown if anunknown protocol is specified.
    84. 84. © 1999 Elliotte Rusty Harold 04/27/13getRequestMethod()• The getRequestMethod() methodreturns the string form of the requestmethod currently set for theURLConnection. GET is the defaultmethod.
    85. 85. © 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
    86. 86. © 1999 Elliotte Rusty Harold 04/27/13For example,try {URL u = newURL("");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) { //...
    87. 87. © 1999 Elliotte Rusty Harold 04/27/13usingProxy• The boolean usingProxy() methodreturns true if web connections are beingfunneled through a proxy server, false iftheyre not.
    88. 88. © 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.
    89. 89. © 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: closeContent-type: text/html<HTML><HEAD><TITLE>302 Moved Temporarily</TITLE></HEAD><BODY><H1>Moved Temporarily</H1>The document has moved <AHREF="">here</A>.<P></BODY></HTML>
    90. 90. © 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.
    91. 91. © 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.
    92. 92. © 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–
    93. 93. © 1999 Elliotte Rusty Harold 04/27/13Questions?