7

我有一些工作的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

现在访问日志不包含用户名/密码/请求方法。但是,Web 服务现在抛出一个异常,表明它没有收到任何用户名/密码。

我在客户端代码中做错了什么?我还尝试使用“setRequestProperty”而不是“addRequestProperty”,它具有相同的损坏行为。

4

1 回答 1

7

我实际上在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
于 2013-03-21T15:49:37.753 回答