HttpUrlConnection addRequestProperty Method Not Passing Parameters

httpurlconnection, java, parameters, post

Solution

I actually found the answer in another question on stackoverflow.

The correct code should be:

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

Problem

I have some working java code which does the following: ``` 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 ``` However, I noticed that my webserver access log contained the plaintext password for all of the users who connected. I would like to get this out of the access log, but the webserver admins claim that this needs to be changed in my code and not via webserver config. I tried changing the code to the following: ``` 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 ``` Now the access log does not contain the username/password/request method. However, the webservice now throws an exception indicating that it didn't receive any username/password. What did I do wrong in my client code? I also tried using "setRequestProperty" instead of "addRequestProperty" and it had the same broken behavior.

Original source