Download URL en Java

Document related concepts
no text concepts found
Transcript
URLs en Java
1
Contenido
• La clase URL
• Acceso al contenido de una URL
• La clase URLEncoder
• La clase URLConnection
2
URLs
Los programas Java que interactúan en Internet utilizan URLs para
encontrar los recursos que quieren accesar.
Los programas en Java utilizan la clase URL para representar una dirección
URL.
protocol://hostname[:port]/path/filename#section
NOTA: El término URL puede ser ambiguo es necesario distinguir entre las
direcciones URL y los objetos URL.
3
Constructores URL
URL(String spec)
URL(String protocol, String host, int port, String file)
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
URL(String protocol, String host, String file)
URL(URL context, String spec)
URL(URL context, String spec, URLStreamHandler handler)
4
Creación de URLs
La manera mas simple de crear un objeto URL es mediante un string en la forma
clásica utilizada en el Web.
Por ejemplo el URL de la OMG (Object Management Group) es :
http://www.omg.org/
En un programa Java, se puede pasar un string con este texto para crear un objeto
URL:
URL omg = new URL("http://www.omg.org/");
Nota: Una vez creado el objeto URL no se podrán cambiar sus atributos
(protocol, host name, filename, or port number).
5
Indice de ejemplos
Ejemplo 1 Creación de URLs
Ejemplo 2 URLs relativos, getDocumentBase()
Ejemplo 3 Parsing URLs
Ejemplo 4 Contenido de un URL
Ejemplo 5 Object getContent()
Ejemplo 6 URLEncoder
Ejemplo 7 queryString
6
Indice de ejemplos
Ejemplo 7 queryString
Ejemplo 8 URLConnection (GET)
Ejemplo 9 URLConnection (POST)
7
Ejemplo 1
import java.net.*;
public class URLConstructorTest1 {
public static void main (String args[]) {
URL webURL, ftpURL;
try {
webURL = new URL("http://www.macfaq.com/vendor.html");
System.out.println(webURL);
ftpURL = new URL("ftp://ftp.macfaq.com/pub/");
System.out.println(ftpURL);
}
catch (MalformedURLException e) {
System.err.println(e);
}
}
}
8
Cracion de URLs Relativos
URL(URL baseURL, String relativeURL)
Por ejemplo, dadas 2 URLs:
http://cs.mty.itesm.mx/rperez/DADI/SDistMiddleware.pdf/
http://cs.mty.itesm.mx/rperez/DADI/Java.pdf/
Se pueden crear objetos URL para estas páginas de manera relativa a su URL de base
http://cs.mty.itesm.mx/rperez/DADI/ :
URL dadi = new URL(" http://cs.mty.itesm.mx/rperez/DADI/");
URL dadiMidWare = new URL(dadi, " SDistMiddleware.pdf ");
URL dadiJava = new URL(dadi, " Java.pdf ");
9
MalformedURLException
Los 4 constructores de la clase URL arrojan MalformedURLException si los
argumentos se refieren a un protocolo null o desconocido :
try {
URL myURL = new URL(. . .)
} catch (MalformedURLException e) {
...
// Código de manejo de excepción
...
}
10
Otras Fuentes de URLs
Existen otros metodos de la librería de clases de Java que regresan como
resultado un URL, por ejemplo en la clase java.applet.Applet:
URL getDocumentBase()
Regresa el URL de la página de base de un Applet
URL getCodeBase()
Regresa el URL del Applet
11
Ejemplo 2
import java.net.*;
import java.applet.Applet;
public class URLConstructorTest4 extends Applet {
public void init () {
URL u1, u2;
u1 = getDocumentBase();
System.out.println(u1);
try {
u2 = new URL(u1, "vendor.html");
System.out.println(u2);
}
catch (MalformedURLException e) {
System.err.println(e);
}
}
}
12
Acceso a los campos del URL
String getProtocol()
String getHost()
int getPort()
Si no se especificó, regresa “-1”
String getFile()
Si no existe regresa “/”
String getRef()
Si no existe regresa “null”
13
Ejemplo 3
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://java.sun.com:80/docs/books/"
+ "tutorial/index.html#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("host = " + aURL.getHost());
System.out.println("filename = " + aURL.getFile());
System.out.println("port = " + aURL.getPort());
System.out.println("ref = " + aURL.getRef());
}
}
14
Ejemplo (Cont…)
Información desplegada por el programa:
protocol = http
host = java.sun.com
filename = /docs/books/tutorial/index.html
port = 80
ref = DOWNLOADING
15
Contenido del URL
InputStream openStream()
Abre una conexión con el recurso del URL y regresa un InputStream del
que se pueden leer datos. Los datos no son interpretados y no se incluyen
headers HTTP.
URLConnection openConnection()
Abre un socket y se comunica directamente con el servidor. Permite leer
todo lo que envia el servidor incluyendo los headers HTTP.
Object getContent()
Recibe los datos del URL y trata de asignarselo a un objeto del tipo
apropiado. Si recibe texto regresa un InputStream si recibe una imagen
regresa un ImageProducer, etc.
16
Ejemplo 4
import java.net.*;
import java.io.*;
public class viewsource {
public static void main (String args[]) {
String thisLine;
URL u;
if (args.length > 0) {
//Open the URL for reading
try {
u = new URL(args[0]);
// now turn the URL into a DataInputStream
try {
DataInputStream theHTML = new DataInputStream(u.openStream());
17
Ejemplo 4 (Cont…)
try {
while ((thisLine = theHTML.readLine()) != null) {
System.out.println(thisLine);
} // while loop ends here
} // end try
catch (Exception e) {
System.err.println(e);
}
} // end try
catch (Exception e) {
System.err.println(e);
}
18
Ejemplo 4 (Cont…)
} // end try
catch (MalformedURLException e) {
System.err.println(args[0] + " is not a parseable URL");
System.err.println(e);
}
} // end if
} // end main
} // end viewsource
19
import java.net.*;
import java.io.*;
Ejemplo 5
public class getobject {
public static void main (String args[]) {
String thisLine;
URL u;
if (args.length > 0) {
//Open the URL for reading
try {
u = new URL(args[0]);
try {
Object o = u.getContent();
System.out.println("I got a " + o.getClass().getName());
} // end try
20
Ejemplo 5 (Cont…)
catch (Exception e) {
System.err.println(e);
}
} // end try
catch (MalformedURLException e) {
System.err.println(args[0] + " is not a parseable URL");
System.err.println(e);
}
} // end if
} // end main
} // end getobject
21
Clase URLEncoder
Uno de los problemas que enfrentan los diseñadores de sistemas Web son las
diferencias entre los sistemas operativos.
Ejemplos:
Algunos sistemas permiten espacios en blanco en los nombres de archivos pero
las URL no los aceptan.
Algunos sistemas permiten el símbolo # en el nombre de un archivo pero una
URL lo interpretaría com que se termino el nombre del archivo y comienza el
anchor.
22
Ejemplo 6
import java.net.URLEncoder;
import java.io.*;
public class encodeTest {
public static void main(String args[]) {
try {
System.out.println(URLEncoder.encode("This string has spaces", "UTF-8"));
System.out.println(URLEncoder.encode("This*string*has*stars", "UTF-8"));
System.out.println(URLEncoder.encode("This%string%has%percent%signs", "UTF-8"));
System.out.println(URLEncoder.encode("This+string+has+pluses", "UTF-8"));
System.out.println(URLEncoder.encode("This/string/has/slashes", "UTF-8"));
System.out.println(URLEncoder.encode("This\"string\"has\"quote\"marks", "UTF-8"));
23
Ejemplo 6
System.out.println(URLEncoder.encode("This:string:has:colons", "UTF-8"));
System.out.println(URLEncoder.encode("This.string.has.periods", "UTF-8"));
System.out.println(URLEncoder.encode("This=string=has=equals=signs", "UTF-8"));
System.out.println(URLEncoder.encode("This&string&has&ampersands", "UTF-8"));
}
catch (UnsupportedEncodingException e) {
System.err.println(e);
}
}
}
24
Ejemplo 6 (Cont)
This+string+has+spaces
This%2astring %2ahas %2astars
This %25string %25has %25percent %25signs
This %2bstring %2bhas %2bpluses
SALIDA
DEL
ENCODER
This %2fstring %2fhas %2fslashes
This %22string %22has %22quote %22marks
This %3astring %32has %3acolons
This %2aestring %2ehas %2eperiods
This %3dstring%3dhas%3dequals%3dsigns
This%26string%26has%26ampersands
import java.net.URLEncoder;
25
Ejemplo 7
public class queryString {
String query;
public queryString(Object name, Object value) {
query = URLEncoder.encode(name.toString()) + "=" +
URLEncoder.encode(value.toString());
}
public void add(Object name, Object value) {
query += "&" + URLEncoder.encode(name.toString()) + "=" +
URLEncoder.encode(value.toString());
}
public String toString() {
return query;
}
}
26
Clase URLConnection
• Se obtiene a partir de una URL mediante le método
openConnection()
•Representa la conexión, (No el URL)
• Mas control que el URL
• Puede escribir en la conexión (puede enviar datos en POST).
• Puede asignar valores a los headers.
• Muy ligada a HTTP
27
Métodos URLConnection
• Crear un objeto URL
• Ejecutar el método openConnection(), este regresa un objeto
del tipo URLConnection
• Se configuran los parámetros de la conexión
• Se establece la conexión mediante el método connect()
28
Ejemplo 8
import java.net.*;
import java.io.*;
public class google {
public static void main (String[] args) {
String querystring = "";
for (int i = 0; i < args.length; i++) {
querystring += args[i] + " ";
}
querystring = querystring.trim();
29
Ejemplo 8 (Cont…)
try {
querystring = "q=" + URLEncoder.encode(querystring, "UTF-8");
String thisLine;
URL u = new URL("http://www.google.com/search?" + querystring);
URLConnection uc = u.openConnection();
uc.setRequestProperty("User-Agent","");
uc.connect();
Requerido por
google
BufferedReader theHTML = new BufferedReader(new
InputStreamReader(uc.getInputStream()));
while ((thisLine = theHTML.readLine()) != null) {
System.out.println(thisLine);
} // while loop ends here
}
30
Ejemplo 8
catch (UnsupportedEncodingException e) {
System.err.println(e);
}
catch (MalformedURLException e) {
System.err.println(e);
}
catch (IOException e) {
System.err.println(e);
}
}
}
31
Ejemplo 9
Usando POST
import java.net.*;
import java.io.*;
public class NamePost {
public static void main(String[] args) throws Exception {
URL url = new URL("http://10.17.40.21/servlet/HelloNamePost");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(
connection.getOutputStream());
out.println("name=" + args[0]);
out.close();
32
Ejemplo 9 (Cont …)
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
33