Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 13
  1. #1

    [JAVA] Classe Url, Scrivere un metodo post come risposta a una form

    Salve a tutti, ringrazio anticipatamente chi mi risponderà. Vi spiego cosa voglio fare: In parole povere vorrei creare un programmino java che accede ad un sito web in cui c'è un form di login con 1 campo di scelta e 2 campi area di testo(nome utente e password).

    Ho provato con questo codice:

    codice:
    import java.io.*; 
    import java.net.*; 
    import java.util.*;
    
    public class PostTest {
    public static void main(String[] args) {
    	
    	try {
    		String fileName = "PostTest.properties";
    		Properties props = new Properties();
    		FileInputStream in = new FileInputStream(fileName);
    		props.load(in);
    		URL url = new URL(props.getProperty("URL"));
    		props.remove("URL");
    		String r = doPost(url, props);
    		System.out.println(r);
    		} 
    	catch (IOException exception) {System.out.println("Error: " + exception);
    	
    }
    }
    
    
    public static String doPost(URL url, Properties nameValuePairs) 
    throws IOException{
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    
    PrintWriter out = new PrintWriter(connection.getOutputStream());
    Enumeration enumd = nameValuePairs.keys();
    while (enumd.hasMoreElements()) {
    String name = (String)enumd.nextElement();
    String value = nameValuePairs.getProperty(name);
    char ch;
    if(enumd.hasMoreElements())
    ch = '&';
    else
    ch = '\n';
    out.print(name + "="+URLEncoder.encode(value) + ch);
    }
    out.close();
    BufferedReader in;
    
    try {
    in = new BufferedReader(new 
    InputStreamReader(connection.getInputStream()));
    }
    
    catch (FileNotFoundException exception) {
    	
    	InputStream err = ((HttpURLConnection)connection).getErrorStream();
    	if(err == null) throw exception;
    	in = new BufferedReader(new InputStreamReader(err));
    	}
    
    
    	StringBuffer response= new StringBuffer();
    	String line;
    	while ((line = in.readLine()) != null)
    	response.append(line + "\n");
    	in.close();
    	return response.toString();
    	}
    	}


    Nel file PostTest.properties ci sono i dati da inserire nella form.

    Ora il problema è che usando questo codice riesco ad inserire nome utente e password ma non riesco a selezionare il campo di scelta e quindi ad inviare correttamente la richiesta post al server.

    C'è qualcuno che potrebbe aiutarmi? anche sconvolgendo il mio codice naturalmente.... sono iterativo e incrementale

    Grazie in anticipo per le risposte.

  2. #2
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    posta l'html del form: fondamentalmente al linguaggio lato server interessa solo sapere il nome dell'elemento del form e il value, il tipo ha importanza "nulla"
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  3. #3
    codice:
    <script type="text/javascript">
    	var lastType = "";
    	function changeAction(type) {
    		if(type=='status') {
    			
    			if(document.status.Uni.value == '') {
    				alert('NO SERVER SELECTED !');
    			} else {
    				var url = "http://" + document.status.Uni.value;
    				document.status.action = url;
    				document.status.Uni.value = '';
    			}			
    			
    		} else {
    			if(document.formular.Uni.value == '') {
    				alert('NO SERVER SELECTED !');
    			} else {
    				var url = "http://" + document.formular.Uni.value;
    				var n = new Date();
    				document.formular.antiback.value=n.getTime();
    				document.formular.action = url;
    			}
    		}
    	}
    </script>
    
    <form action="" method="POST" name="formular" target="_top" onsubmit="changeAction('login');">
    	<table width=906 align="center" cellpadding="0" cellspacing="0">
    		<tr>
    			<td width="53" background="vendetta/img/left_bg.jpg"></td>
    			<td valign=top>
    				<table width="799" border="0" cellspacing="0" cellpadding="0" height="100%">
                    			<tr>
    
                        				<td background="vendetta/img/login_bg_left.jpg" height="63" width="175"></td>
                        				<td background="vendetta/img/login_bg.jpg" height="63" width="449" align="center">
    
    
    
    <select name="Uni" class="loginbox" size=1>
    <option value=s1.vendetta1923.it/vendetta/login.php>Server1</option><option value=s2.vendetta1923.it/vendetta/login.php>Server2</option><option value=s3.vendetta1923.it/vendetta/login.php>Server3</option><option value=s4.vendetta1923.it/vendetta/login.php>Server4</option><option value=s5.vendetta1923.it/vendetta/login.php>Server5</option><option value=s6.vendetta1923.it/vendetta/login.php>Server6</option></select>
    
    		    			<input type=hidden name="layout" value=1>
    
    						<input type=hidden name="antiback" id="antiback" value=1190153061 >
                   			<input type=text name="ln" value="" size=10 maxlength=30 class="loginbox">
    						<input type=password name="pw" value="" size=10 maxlength=30 class="loginbox">
                   			<input type=image src="vendetta/img/login_bt.jpg" width="50" height="16">
    						
    
    			   						    			<font class="content_text" style="font-size: 0.7em;">Con il mio login accetto i Termini d`utilizzo</font>
                        				</td>
    </form>
    Ecco il codice della form, e ho messo anche il pezzo di script, non sò forse potrebbe dipendere proprio da qualcosa nello script... grazie per l'interessamento

  4. #4
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    Visto che la funzione changeAction riceve come argomento "login", type="login" e bisogna codificare un'altra coppia chiave/valore che non è presente nel tuo file di properties

    codice:
    String append1 = "anitback="+(new Date()).getTime()/1000+"&";
    Poi l'url verso cui fare il post proviene dalla select... non so a che cosa serva (è un gioco online?), scegline uno e sei apposto.
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  5. #5
    Si l'url è di un gioco online, e infatti ho scelto uno dei campi della select. Per quanto riguarda l'argomento login devo aggiungere la stringa di codice che mi hai postato nel file Properties? Adesso il mio file properties contiene questi dati:

    URL=http://vendetta1923.it/vendetta/login.php?
    ln=NomeUtente
    pw=******
    Uni=s5.vendetta1923.it/vendetta/login.php
    anitback=(new Date()).getTime()/1000


    devo aggiungere altro?

    Ho provato con questo file ma non cambia nulla, nel senso che mi stampa sulla console sempre la pagina di login e non la risposta.

  6. #6
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    No, attenzione, tu in quel modo non stai facendo un POST, pare più un GET (col ? etc etc) e mi scuso anch'io per non averci fatto caso prima. Allora ti rimando alla lettura di questo thread

    http://forum.html.it/forum/showthrea...ight=post+http

    dove ho segnalato una comoda classe di commons per trattare comunicazioni con server, oppure, se vuoi codificare tu tutto a manina più sotto nello stesso thread c'è un link ad un articolo comparso su javaworld.com.

    EDIT: ecco l'esempio con quella libreria di commons:

    http://jakarta.apache.org/httpcompon...hods/post.html
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  7. #7
    Si in effetti hai ragione è un GET perchè gli sto passando la query string. Cmq non importa o con il metodo GET o con il metodo POST mi va bene.
    Anche io credevo di fare una GET, ma il codice che ho scritto sopra l'avevo visto su un pdf di un università e l'avevo modificato per il mio caso specifico, ma stranamente diceva di utilizzare la POST.

    Tu che mi consigli? P.s. naturalmente non sto usando una servlet ma un programma java senza GUI che mi stampa su console(lo dico per essere chiaro).

  8. #8
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    ti consiglio quella package di commons: più chiara di quella non c'è niente.

    codice:
    PostMethod post = new PostMethod("http://s5.vendetta1923.it/vendetta/login.php");
    NameValuePair[] data = {
      new NameValuePair("ln", "NomeUtente"),
      new NameValuePair("pw", "PasswordUtente"),
      new NameValuePair("antiback", ((new Date()).getTime()/1000)+"") //che brutta questa :zizi: 
    };
    post.setRequestBody(data);
    // execute method and handle any error responses.
      ...
    InputStream in = post.getResponseBodyAsStream();
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  9. #9
    Ho inserito il file .jar del package che mi hai indicato nel build path di eclipse, ho fatto le seguenti importazioni:

    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Date;

    import org.apache.commons.httpclient.*;
    import org.apache.commons.httpclient.methods.PostMethod;

    e ho messo il codice che sopra mi hai dato. Solo che mi da un errore a runtime:

    codice:
    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    	at org.apache.commons.httpclient.HttpMethodBase.<clinit>(HttpMethodBase.java:104)
    	at connettore.Main.main(Main.java:17)
    Ecco il codice :

    codice:
    package connettore;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Date;
    
    import org.apache.commons.httpclient.*;
    import org.apache.commons.httpclient.methods.PostMethod;
    
    
    
    public class Main {
    
    
    	public static void main(String[] args) throws IOException {
    		
    		PostMethod post = new PostMethod("http://s5.vendetta1923.it/vendetta/login.php");
    		NameValuePair[] data = {
    		  new NameValuePair("ln", "NomeUtente"),
    		  new NameValuePair("pw", "*****"),
    		  new NameValuePair("antiback", ((new Date()).getTime()/1000)+"") 
    		};
    		post.setRequestBody(data);
    //		 execute method and handle any error responses.
    		  
    		try {
    			InputStream in = post.getResponseBodyAsStream();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} 
    
    	}
    
    }
    Dove sbaglio?

  10. #10
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    Probabilmente ha bisogno di qualche altro package:

    http://commons.apache.org/logging/

    scaricalo e mettilo nel build path di eclipse.
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.