HttpUrlConnection addRequestProperty Method Not Passing Parameters

微笑、不失礼 提交于 2020-01-03 08:58:10

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/15551676/httpurlconnection-addrequestproperty-method-not-passing-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!