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

Acceder a páginas web con Java, que tengan login y password

Estas en el tema de Acceder a páginas web con Java, que tengan login y password en el foro de Java en Foros del Web. Hola amig@s tengo que acceder a una página web con java, pero está página tiene login y password, lso cuales poseo. Se como acceder a ...
  #1 (permalink)  
Antiguo 18/02/2011, 03:51
 
Fecha de Ingreso: febrero-2011
Mensajes: 8
Antigüedad: 13 años, 2 meses
Puntos: 0
Acceder a páginas web con Java, que tengan login y password

Hola amig@s tengo que acceder a una página web con java, pero está página tiene login y password, lso cuales poseo.
Se como acceder a una página web que no tenga identificacción pero no se como hacerlo cuando la página pide login y password.
Por favor, alguien me podría ayudar. Es muy urgente.
Gracias de antemano.
  #2 (permalink)  
Antiguo 18/02/2011, 06:48
 
Fecha de Ingreso: febrero-2011
Mensajes: 8
Antigüedad: 13 años, 2 meses
Puntos: 0
Por favor, alguien me puede ayudar

Por favor, que alguien me ayude a solucionar este problema.
  #3 (permalink)  
Antiguo 18/02/2011, 08:51
Avatar de nup_  
Fecha de Ingreso: noviembre-2010
Mensajes: 265
Antigüedad: 13 años, 5 meses
Puntos: 32
Respuesta: Acceder a páginas web con Java, que tengan login y password

Hola:

Mira el API HTTPClient de la gente de Apache:
http://hc.apache.org/httpcomponents-...-ga/index.html

Un ejemplo con autenticación:
http://hc.apache.org/httpcomponents-...ntication.java


saludos;

Nup_
  #4 (permalink)  
Antiguo 21/02/2011, 04:13
 
Fecha de Ingreso: febrero-2011
Mensajes: 8
Antigüedad: 13 años, 2 meses
Puntos: 0
Respuesta: Acceder a páginas web con Java, que tengan login y password

Hola, he estado mirando eso pero no me entero de nada, me puedes poner un ejemplo concreto explicandomelo por favor.
Sería acceder a una pagina que tiene usuario y contraseña y poder leer el contenido de la pagina a la que accedería al loguearse.
Muchas gracias y un saludo.
  #5 (permalink)  
Antiguo 21/02/2011, 13:16
Avatar de nup_  
Fecha de Ingreso: noviembre-2010
Mensajes: 265
Antigüedad: 13 años, 5 meses
Puntos: 32
Respuesta: Acceder a páginas web con Java, que tengan login y password

Hola xivela:

El API HTTPClient q te puse sirve para lo q quieres hacer también. De hecho unos de los ejemplos es una autenticación basada en formulario:
http://hc.apache.org/httpcomponents-...FormLogin.java

Me tomé la libertad de modificar un poco ese ejemplo para ajustarlo a tu página. Este es el código:
Código Java:
Ver original
  1. /*
  2.  * ====================================================================
  3.  *
  4.  *  Licensed to the Apache Software Foundation (ASF) under one or more
  5.  *  contributor license agreements.  See the NOTICE file distributed with
  6.  *  this work for additional information regarding copyright ownership.
  7.  *  The ASF licenses this file to You under the Apache License, Version 2.0
  8.  *  (the "License"); you may not use this file except in compliance with
  9.  *  the License.  You may obtain a copy of the License at
  10.  *
  11.  *      http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  *  Unless required by applicable law or agreed to in writing, software
  14.  *  distributed under the License is distributed on an "AS IS" BASIS,
  15.  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  *  See the License for the specific language governing permissions and
  17.  *  limitations under the License.
  18.  * ====================================================================
  19.  *
  20.  * This software consists of voluntary contributions made by many
  21.  * individuals on behalf of the Apache Software Foundation.  For more
  22.  * information on the Apache Software Foundation, please see
  23.  * <http://www.apache.org/>.
  24.  *
  25.  */
  26.  
  27. package org.apache.http.examples.client;
  28.  
  29. import java.util.ArrayList;
  30. import java.util.List;
  31. import org.apache.http.HttpEntity;
  32. import org.apache.http.HttpResponse;
  33. import org.apache.http.NameValuePair;
  34. import org.apache.http.client.entity.UrlEncodedFormEntity;
  35. import org.apache.http.client.methods.HttpGet;
  36. import org.apache.http.client.methods.HttpPost;
  37. import org.apache.http.cookie.Cookie;
  38. import org.apache.http.impl.client.DefaultHttpClient;
  39. import org.apache.http.message.BasicNameValuePair;
  40. import org.apache.http.protocol.HTTP;
  41. import org.apache.http.util.EntityUtils;
  42.  
  43. /**
  44.  * A example that demonstrates how HttpClient APIs can be used to perform
  45.  * form-based logon.
  46.  */
  47. public class ClientFormLogin {
  48.  
  49.     public static void main(String[] args) throws Exception {
  50.  
  51.         System.out.println("Starting");
  52.        
  53.         DefaultHttpClient httpclient = new DefaultHttpClient();
  54.         try {
  55.             HttpGet httpget = new HttpGet("https://www.image.net/xads/actions/login.do");
  56.  
  57.             HttpResponse response = httpclient.execute(httpget);
  58.             HttpEntity entity = response.getEntity();
  59.  
  60.             System.out.println("Login form get: " + response.getStatusLine());
  61.             EntityUtils.consume(entity);
  62.  
  63.             // Mostramos las cookies
  64.             System.out.println("Initial set of cookies:");
  65.             List<Cookie> cookies = httpclient.getCookieStore().getCookies();
  66.             if (cookies.isEmpty()) {
  67.                 System.out.println("None");
  68.             } else {
  69.                 for (int i = 0; i < cookies.size(); i++) {
  70.                     System.out.println("- " + cookies.get(i).toString());
  71.                 }
  72.             }
  73.  
  74.             HttpPost httpost = new HttpPost("https://www.image.net/xads/actions/processlogon.do");
  75.            
  76.             /*
  77.              * Poner aki tus credenciales de autenticación
  78.             */
  79.             String usuario = "usuario";
  80.             String password = "password";
  81.  
  82.             // Variables a mandar
  83.             List <NameValuePair> nvps = new ArrayList <NameValuePair>();
  84.             nvps.add(new BasicNameValuePair("screen", "post_login"));
  85.             nvps.add(new BasicNameValuePair("lang_change", ""));
  86.             nvps.add(new BasicNameValuePair("forward_url", ""));
  87.             nvps.add(new BasicNameValuePair("login", usuario));
  88.             nvps.add(new BasicNameValuePair("password", password));
  89.  
  90.             httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
  91.  
  92.             response = httpclient.execute(httpost);
  93.             entity = response.getEntity();
  94.  
  95.             System.out.println("Login form get: " + response.getStatusLine());
  96. //          EntityUtils.consume(entity);
  97.            
  98.             // Escribimos la respuesta de la página hacia
  99.             //   un outputstream. En este caso: la consola.
  100.             entity.writeTo(System.out);
  101.            
  102.             // Mostramos las cookies
  103.             System.out.println("Post logon cookies:");
  104.             cookies = httpclient.getCookieStore().getCookies();
  105.             if (cookies.isEmpty()) {
  106.                 System.out.println("None");
  107.             } else {
  108.                 for (int i = 0; i < cookies.size(); i++) {
  109.                     System.out.println("- " + cookies.get(i).toString());
  110.                 }
  111.             }
  112.  
  113.         } finally {
  114.             // When HttpClient instance is no longer needed,
  115.             // shut down the connection manager to ensure
  116.             // immediate deallocation of all system resources
  117.             httpclient.getConnectionManager().shutdown();
  118.         }
  119.     }
  120. }

Para ejecutarlo necesitas bajar las librerías del HttpClient:
http://apache.mirrors.tds.net//httpc...nt-4.1-bin.zip
y añadir todos los .jar q hayan en la carpeta lib a tu CLASSPATH.

Las URLs del código son las de tu sitio (www.imagen.net) así q si pones bien el user y pass debe funcionar.

saludos;

Nup_
  #6 (permalink)  
Antiguo 22/02/2011, 04:50
 
Fecha de Ingreso: febrero-2011
Mensajes: 8
Antigüedad: 13 años, 2 meses
Puntos: 0
Respuesta: Acceder a páginas web con Java, que tengan login y password

Hola, muchas gracias, había estando mirando el códigoq ue me mandabas pero yo solo ponía lo de contraseña y paswword.
he visto que al finalizar me devuelve unas cookies, eso es lo que tengo que mandar a partir de ahora para ver el html de las otras páginas:
por ejemplo para ver el contentido de:
http://www.image.net/xads/actions/layout/category.do?sorted_product_nav_root=15319&category _nav=15319

Tengo que poner el código que me indicaste tu y luego que más?

Muchas gracias.

Xivela
  #7 (permalink)  
Antiguo 22/02/2011, 05:18
 
Fecha de Ingreso: febrero-2011
Mensajes: 8
Antigüedad: 13 años, 2 meses
Puntos: 0
Respuesta: Acceder a páginas web con Java, que tengan login y password

Hola de nuevo:
Para leer paginas internas he hecho esto, no se si es correcto:

httpost = new HttpPost("http://www.image.net/xads/actions/layout/category.do?sorted_product_nav_root=15319&category _nav=15319");
response = httpclient.execute(httpost);

entity = response.getEntity();
entity.writeTo(System.out);


Si quiero que me devuelva todo el html en un string, que hago?

Muchisimas gracias
  #8 (permalink)  
Antiguo 22/02/2011, 07:01
Avatar de nup_  
Fecha de Ingreso: noviembre-2010
Mensajes: 265
Antigüedad: 13 años, 5 meses
Puntos: 32
Respuesta: Acceder a páginas web con Java, que tengan login y password

Hola:

Usa un ByteArrayOutputStream (http://download.oracle.com/javase/1....putStream.html).

Ejemplo:
Código Java:
Ver original
  1.             entity.writeTo(baos);
  2.             System.out.println(baos.toString("UTF-8"));

saludos;

Nup_

Etiquetas: conexion, contraseña, login, password, url, usuarios
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 22:27.