我有一些可以执行以下操作的 java 代码:
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
但是,我注意到我的网络服务器访问日志包含所有连接用户的明文密码。我想从访问日志中删除它,但网络服务器管理员声称这需要在我的代码中而不是通过网络服务器配置进行更改。
我尝试将代码更改为以下内容:
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
现在访问日志不包含用户名/密码/请求方法。但是,网络服务现在抛出一个异常,表明它没有收到任何用户名/密码。
我的客户端代码做错了什么?我还尝试使用“setRequestProperty”而不是“addRequestProperty”,但它有同样的错误行为。
最佳答案
我实际上在 another question on stackoverflow. 中找到了答案
正确的代码应该是:
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
关于java - HttpUrlConnection addRequestProperty 方法不传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15551676/