elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Únete al Grupo Steam elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  enviar formulario de una pagina con java
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: enviar formulario de una pagina con java  (Leído 2,714 veces)
soru13

Desconectado Desconectado

Mensajes: 246



Ver Perfil
enviar formulario de una pagina con java
« en: 8 Marzo 2013, 23:52 pm »

Hola, he estado mirando en la librería java.net algún método para poder cargar una página con java.net.URL y enviar el formulario que contiene ésta página, pero no encuentro nada.

Sólamente he conseguido cargar la página, pero no encuentro ningún método, a ver si alguien me puede orientar para hacer esto.

Este es el poco código que tengo:

Código
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.net.MalformedURLException;
  5. import java.net.URL;
  6. import java.net.URLConnection;
  7.  
  8.  
  9. public class main {
  10.  
  11. public static void main(String[] args) throws IOException {
  12.  
  13. URL url = new URL("http://www.google.es/");
  14. URLConnection con = url.openConnection();
  15.  
  16. }
  17.  
  18. }
  19.  

Gracias.


En línea

1mpuls0


Desconectado Desconectado

Mensajes: 1.186


Ver Perfil
Re: enviar formulario de una pagina con java
« Respuesta #1 en: 9 Marzo 2013, 00:02 am »

Hay una librería de apache.
Tal vez podrías usarla pero si no quieres usar otras librerías esto te puede servir.

http://www.codejava.net/java-se/networking/an-http-utility-class-to-send-getpost-request

Saludos.


En línea

abc
soru13

Desconectado Desconectado

Mensajes: 246



Ver Perfil
Re: enviar formulario de una pagina con java
« Respuesta #2 en: 9 Marzo 2013, 00:17 am »

Es justo lo que andaba buscando, muchas gracias.  ;-)
En línea

1mpuls0


Desconectado Desconectado

Mensajes: 1.186


Ver Perfil
Re: enviar formulario de una pagina con java
« Respuesta #3 en: 9 Marzo 2013, 08:02 am »

Voy a dejar las clases con su respectivo autor y fuente por si llegara a desaparecer el link.


Código
  1. package net.codejava.networking;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.io.OutputStreamWriter;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. import java.net.URLEncoder;
  11. import java.util.ArrayList;
  12. import java.util.Iterator;
  13. import java.util.List;
  14. import java.util.Map;
  15.  
  16. /**
  17.  * This class encapsulates methods for requesting a server via HTTP GET/POST and
  18.  * provides methods for parsing response from the server.
  19.  *
  20.  * @author www.codejava.net
  21.  *
  22.  */
  23. public class HttpUtility {
  24.  
  25.    /**
  26.      * Represents an HTTP connection
  27.      */
  28.    private static HttpURLConnection httpConn;
  29.  
  30.    /**
  31.      * Makes an HTTP request using GET method to the specified URL.
  32.      *
  33.      * @param requestURL
  34.      *            the URL of the remote server
  35.      * @return An HttpURLConnection object
  36.      * @throws IOException
  37.      *             thrown if any I/O error occurred
  38.      */
  39.    public static HttpURLConnection sendGetRequest(String requestURL)
  40.            throws IOException {
  41.        URL url = new URL(requestURL);
  42.        httpConn = (HttpURLConnection) url.openConnection();
  43.        httpConn.setUseCaches(false);
  44.  
  45.        httpConn.setDoInput(true); // true if we want to read server's response
  46.        httpConn.setDoOutput(false); // false indicates this is a GET request
  47.  
  48.        return httpConn;
  49.    }
  50.  
  51.    /**
  52.      * Makes an HTTP request using POST method to the specified URL.
  53.      *
  54.      * @param requestURL
  55.      *            the URL of the remote server
  56.      * @param params
  57.      *            A map containing POST data in form of key-value pairs
  58.      * @return An HttpURLConnection object
  59.      * @throws IOException
  60.      *             thrown if any I/O error occurred
  61.      */
  62.    public static HttpURLConnection sendPostRequest(String requestURL,
  63.            Map<String, String> params) throws IOException {
  64.        URL url = new URL(requestURL);
  65.        httpConn = (HttpURLConnection) url.openConnection();
  66.        httpConn.setUseCaches(false);
  67.  
  68.        httpConn.setDoInput(true); // true indicates the server returns response
  69.  
  70.        StringBuffer requestParams = new StringBuffer();
  71.  
  72.        if (params != null && params.size() > 0) {
  73.  
  74.            httpConn.setDoOutput(true); // true indicates POST request
  75.  
  76.            // creates the params string, encode them using URLEncoder
  77.            Iterator<String> paramIterator = params.keySet().iterator();
  78.            while (paramIterator.hasNext()) {
  79.                String key = paramIterator.next();
  80.                String value = params.get(key);
  81.                requestParams.append(URLEncoder.encode(key, "UTF-8"));
  82.                requestParams.append("=").append(
  83.                        URLEncoder.encode(value, "UTF-8"));
  84.                requestParams.append("&");
  85.            }
  86.  
  87.            // sends POST data
  88.            OutputStreamWriter writer = new OutputStreamWriter(
  89.                    httpConn.getOutputStream());
  90.            writer.write(requestParams.toString());
  91.            writer.flush();
  92.        }
  93.  
  94.        return httpConn;
  95.    }
  96.  
  97.    /**
  98.      * Returns only one line from the server's response. This method should be
  99.      * used if the server returns only a single line of String.
  100.      *
  101.      * @return a String of the server's response
  102.      * @throws IOException
  103.      *             thrown if any I/O error occurred
  104.      */
  105.    public static String readSingleLineRespone() throws IOException {
  106.        InputStream inputStream = null;
  107.        if (httpConn != null) {
  108.            inputStream = httpConn.getInputStream();
  109.        } else {
  110.            throw new IOException("Connection is not established.");
  111.        }
  112.        BufferedReader reader = new BufferedReader(new InputStreamReader(
  113.                inputStream));
  114.  
  115.        String response = reader.readLine();
  116.        reader.close();
  117.  
  118.        return response;
  119.    }
  120.  
  121.    /**
  122.      * Returns an array of lines from the server's response. This method should
  123.      * be used if the server returns multiple lines of String.
  124.      *
  125.      * @return an array of Strings of the server's response
  126.      * @throws IOException
  127.      *             thrown if any I/O error occurred
  128.      */
  129.    public static String[] readMultipleLinesRespone() throws IOException {
  130.        InputStream inputStream = null;
  131.        if (httpConn != null) {
  132.            inputStream = httpConn.getInputStream();
  133.        } else {
  134.            throw new IOException("Connection is not established.");
  135.        }
  136.  
  137.        BufferedReader reader = new BufferedReader(new InputStreamReader(
  138.                inputStream));
  139.        List<String> response = new ArrayList<String>();
  140.  
  141.        String line = "";
  142.        while ((line = reader.readLine()) != null) {
  143.            response.add(line);
  144.        }
  145.        reader.close();
  146.  
  147.        return (String[]) response.toArray(new String[0]);
  148.    }
  149.  
  150.    /**
  151.      * Closes the connection if opened
  152.      */
  153.    public static void disconnect() {
  154.        if (httpConn != null) {
  155.            httpConn.disconnect();
  156.        }
  157.    }
  158. }
  159.  

Código
  1. package net.codejava.networking;
  2.  
  3. import java.io.IOException;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6.  
  7. public class HttpUtilityTester {
  8.  
  9.    /**
  10.      * This program uses the HttpUtility class to send a GET request to
  11.      * Google home page; and send a POST request to Gmail login page.
  12.      */
  13.    public static void main(String[] args) {
  14.        // test sending GET request
  15.        String requestURL = "http://www.google.com";
  16.        try {
  17.            HttpUtility.sendGetRequest(requestURL);
  18.            String[] response = HttpUtility.readMultipleLinesRespone();
  19.            for (String line : response) {
  20.                System.out.println(line);
  21.            }
  22.        } catch (IOException ex) {
  23.            ex.printStackTrace();
  24.        }
  25.        HttpUtility.disconnect();
  26.  
  27.  
  28.        System.out.println("=====================================");
  29.  
  30.        // test sending POST request
  31.        Map<String, String> params = new HashMap<String, String>();
  32.        requestURL = "https://accounts.google.com/ServiceLoginAuth";
  33.        params.put("Email", "your_email");
  34.        params.put("Passwd", "your_password");
  35.  
  36.        try {
  37.            HttpUtility.sendPostRequest(requestURL, params);
  38.            String[] response = HttpUtility.readMultipleLinesRespone();
  39.            for (String line : response) {
  40.                System.out.println(line);
  41.            }
  42.        } catch (IOException ex) {
  43.            ex.printStackTrace();
  44.        }
  45.        HttpUtility.disconnect();
  46.    }
  47. }
  48.  

Autor: www.codejava.net
Fuente: http://www.codejava.net/java-se/networking/an-http-utility-class-to-send-getpost-request

Saludos
En línea

abc
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Enviar formulario a correo « 1 2 »
PHP
lluk 18 9,051 Último mensaje 8 Septiembre 2010, 23:04 pm
por neopuerta360
Enviar formulario automaticamente
PHP
neopuerta360 6 8,805 Último mensaje 28 Septiembre 2010, 19:48 pm
por ~ Yoya ~
Enviar datos de un formulario de una pagina JSP a una clase.
Java
h3ct0r 3 8,134 Último mensaje 22 Febrero 2011, 20:07 pm
por h3ct0r
enviar formulario prototype
Desarrollo Web
kakashi20 0 2,209 Último mensaje 7 Noviembre 2011, 20:07 pm
por kakashi20
Conectar a pagina web de formulario java
Java
soy_nicanor 1 1,394 Último mensaje 21 Agosto 2015, 01:46 am
por soy_nicanor
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines