2013-03-21 13 views
7

ho qualche codice Java di lavoro che esegue le seguenti operazioni:HttpURLConnection addRequestProperty Metodo non passare i parametri

URL myUrl = new URL("http://localhost:8080/webservice?user=" + username + "&password=" + password + "&request=x"); 

HttpURLConnection myConnection = (HttpURLConnection) myUrl.openConnection(); 
myConnection.setRequestMethod("POST"); 

// code continues to read the response stream 

Tuttavia, ho notato che il mio server web log di accesso conteneva la password in chiaro per tutti gli utenti che si sono collegati. Vorrei ottenere questo dal log di accesso, ma gli amministratori del server web sostengono che questo deve essere cambiato nel mio codice e non tramite la configurazione del server web.

Ho provato a cambiare il codice di seguito:

URL myUrl = new URL("http://localhost:8080/webservice"); 

HttpURLConnection myConnection = (HttpURLConnection) myUrl.openConnection(); 
myConnection.setRequestMethod("POST"); 
// start of new code 
myConnection.setDoOutput(true); 
myConnection.addRequestProperty("username", username); 
myConnection.addRequestProperty("password", password); 
myConnection.addRequestProperty("request", "x"); 

// code continues to read the response stream 

Ora il log di accesso non contiene il metodo nome utente/password/richiesta. Tuttavia, il webservice genera un'eccezione che indica che non ha ricevuto alcun nome utente/password.

Cosa ho fatto di sbagliato nel mio codice cliente? Ho anche provato a utilizzare "setRequestProperty" invece di "addRequestProperty" e ha avuto lo stesso comportamento danneggiato.

risposta

7

realtà ho trovato la risposta in another question on stackoverflow.

Il codice corretto dovrebbe essere:

URL myUrl = new URL("http://localhost:8080/webservice"); 

HttpURLConnection myConnection = (HttpURLConnection) myUrl.openConnection(); 
myConnection.setRequestMethod("POST"); 
myConnection.setDoOutput(true); 

DataOutputStream wr = new DataOutputStream(myConnection.getOutputStream()); 
wr.writeBytes("username=" + username + "&password="+password + "&request=x"); 

// code continues to read the response stream 
+0

Si dovrebbe convalidare la tua risposta ;-) – JonesV

+0

Jones e David mi puoi dire che io possa inviare un'immagine come u invio nome utente e password? vedi la mia domanda qui http://stackoverflow.com/questions/27615276/how-to-send-data-to-server –

+0

tutti i post qui ho cercato che sono quasi esattamente uguali e il tuo risolve il mio problema, grazie David! – Rob85

Problemi correlati