HttpUrlConnection的addRequestProperty方法未传递参数

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

然而,我注意到我的Web服务器访问日志包含所有连接用户的明文密码。我想从访问日志中删除这些密码,但Web服务器管理员声称这需要通过我的代码更改,而不是通过Web服务器配置进行更改。
我尝试将代码更改为以下内容:
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

现在访问日志中不包含用户名/密码/请求方法。然而,webservice现在会抛出一个异常,指示它没有收到任何用户名/密码。

我在客户端代码中做错了什么?我还尝试使用“setRequestProperty”而不是“addRequestProperty”,但它的行为仍然有问题。

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

你应该验证你的答案;-) - JonasVautherin
Jones和David,你们能告诉我我是否可以像发送用户名和密码一样发送图像吗?请看我的问题:http://stackoverflow.com/questions/27615276/how-to-send-data-to-server - user4380006
在这里我搜索到的所有帖子几乎都和我的问题完全相同,而你的解决方案正好能解决我的问题,非常感谢你,David! - Rob85

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接