HttpUrlConnection addRequestProperty方法不传递参数

Dav*_*vid 7 java parameters post httpurlconnection

我有一些工作的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
Run Code Online (Sandbox Code Playgroud)

但是,我注意到我的网络服务器访问日志包含所有连接用户的明文密码.我想从访问日志中得到这个,但是网络服务器管理员声称这需要在我的代码中更改,而不是通过webserver配置.

我尝试将代码更改为以下内容:

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
Run Code Online (Sandbox Code Playgroud)

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

我在客户端代码中做错了什么?我也尝试使用"setRequestProperty"而不是"addRequestProperty",它具有相同的破坏行为.

Dav*_*vid 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
Run Code Online (Sandbox Code Playgroud)