HttpUrlConnection addRequestProperty方法不传递参数

时间:2013-03-21 15:28:24

标签: java post parameters 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

但是,我注意到我的网络服务器访问日志包含所有连接用户的明文密码。我想从访问日志中获取此信息,但网络服务器管理员声称需要在我的代码中更改,而不是通过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

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

我的客户端代码出错了什么?我也尝试使用“setRequestProperty”而不是“addRequestProperty”,它也有相同的破坏行为。

1 个答案:

答案 0 :(得分:7)

我实际上在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