Foros del Web » Programación para mayores de 30 ;) » Java »

como mostrar paginas web por url en java

Estas en el tema de como mostrar paginas web por url en java en el foro de Java en Foros del Web. hola no se si el tema este bien formulad pero el caso es el siguiente.... resulta que estoy haciendo un trabajo para la univ de ...
  #1 (permalink)  
Antiguo 24/11/2010, 18:33
 
Fecha de Ingreso: noviembre-2010
Mensajes: 15
Antigüedad: 13 años, 5 meses
Puntos: 0
Pregunta como mostrar paginas web por url en java

hola no se si el tema este bien formulad pero el caso es el siguiente....

resulta que estoy haciendo un trabajo para la univ de servidores y tengo qeu diseñar un servidor proxy, ya tengo la parte de que cuando el cliente resibe la solicitud de una pagina y la tiene en su disco entonces la regresa a ser visuaizada en el navegador...

ahora lo que me falta es lograr que cuando la pagina no esta en disco, el la busque segun la url introducida por el usuario, para despues ser visualizada en el navegador....

he leido que con la funcion URL de java se puede lograr pero la verdad soy principiante y necesito ayuda y aun n he encontrado la manera de hacerlo...

agradezco de antemano su apollo..

un saludo

el codigo que tengo es el siguiente...aun no esta terminado y tiene errores pero si me pueden ayudar a corregirlo seria aun mejor gracias:
package proxy;

/**
*
* @author Liev
*/

import java.net.*;
import java.io.*;
import java.util.*;

public class proxsy extends Thread {
// Servidor HTTP

Socket theConnection;
static File docroot;
static String indexfile = "index.html";

public proxsy(Socket s) {
// Constructor
theConnection = s;
}

public static void main(String[] args) {
// El primer parámetro es el directorio raiz desde donde accede a las
// páginas, y el segundo parámetro es el número del puerto por el que
// escucha. Si no se pasan parámetros, toma el directorio actual y el
// puerto 80 por defecto.

int thePort;
ServerSocket ss;

// Captura el directorio raiz
try {
docroot = new File(args[0]);
}
catch (Exception e) {
docroot = new File("."); // Toma el directorio actual
}

// Captura el puerto para escuchar
thePort=80;

try {
ss = new ServerSocket(thePort);
System.out.println("Aceptando conexiones en el puerto: " + ss.getLocalPort());
//System.out.println("Directorio raiz: " + docroot);
System.out.println("Servidor HTTP en ejecucion...");
while (true) {
proxsy s = new proxsy(ss.accept());
s.start();
}
}
catch (IOException e) {
System.err.println("Servidor abortado");
}
}

public void run() {
// Llamado al thread

String method;
String ct;
String version = "";
File theFile;

try {
PrintStream os = new PrintStream(theConnection.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(theConnection.getInputStream())) ;
String get = br.readLine();
StringTokenizer st = new StringTokenizer(get);
method = st.nextToken();

if (method.equals("GET")) {
String file = st.nextToken();

if (file.endsWith("/")) // Si es un archivo html
file += indexfile;

ct = guessContentTypeFromName(file);
if (st.hasMoreTokens())
version = st.nextToken();

// Ciclo hasta el resto de las lineas de entrada
while ((get = br.readLine()) != null)
if (get.trim().equals(""))
break;
try {
theFile = new File(docroot, file.substring(1,file.length()));
FileInputStream fis = new FileInputStream(theFile);
byte[] theData = new byte[(int) theFile.length()];
// Necesita chequear el numero de bytes leidos hasta aqui
fis.read(theData);


fis.close();
System.out.println("ENTRANDO AL ENVIO DEL MIME");
if (version.startsWith("HTTP/")) { // Envia un encabezado MIME
os.print("HTTP/1.0 200 OK\r\n");
Date now = new Date();
os.print("Fecha: " + now + "\r\n");
os.print("Servidor: shttp 1.0\r\n");
os.print("Content-length: " + theData.length + "\r\n");
os.print("Content-type: " + ct + "\r\n\r\n");
}
// Envia el archivo
os.write(theData);
os.close();
} // fin del try
catch (IOException e) {

URL url= new URL("http://www.google.com");
URLConnection cone = url.openConnection();
BufferedReader datos= new BufferedReader(new InputstreamReader(cone.getInputStream()));
PrintStream datos = new PrintStream(theConnection.getOutputStream());

datos.write();
// BufferedReader datos = new BufferedReader(new InputStreamReader(cone.getInputStream()));

// URLConnection destino= theData.equals(br);
//manejar la url pedida probare poniendole la que primera que pasa el usuario a ver q sucede
/* URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);

in.close();


}

}
else { // El metodo no es "GET"*/}
if (version.startsWith("HTTP/")) { // Envia un encabezado MIME
os.print("HTTP/1.0 501 No Implementado\r\n");
Date now = new Date();
os.print("Fecha: " + now + "\r\n");
os.print("Servidor: shttp 1.0\r\n");
os.print("Content-type: text/html" + "\r\n\r\n");
}
os.println("<HTML><HEAD><TITLE>No Implementado</TITLE></HEAD>");
os.println("<BODY><H2>HTTP Error 501: No Implementado</H2></BODY></HTML>");
os.close();
}
}
catch (IOException e) {
}
try {
theConnection.close();
}
catch (IOException e) {
}
}

public String guessContentTypeFromName(String name) {
System.out.println("ENTRANDO EN EL ENVIO!!!!");
if (name.endsWith(".html") || name.endsWith(".htm"))
return "text/html";
else if (name.endsWith(".txt") || name.endsWith(".java"))
return "text/plain";
else if (name.endsWith(".gif"))
return "image/gif";
else if (name.endsWith(".jpg") || name.endsWith(".jpeg"))
return "image/jpeg";
else
return "text/plain";
}
}

Etiquetas: programacion, proxy, realizar
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 16:27.