java HttpUrlConnection addRequestProperty 方法不传递参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15551676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:01:53  来源:igfitidea点击:

HttpUrlConnection addRequestProperty Method Not Passing Parameters

javapostparametershttpurlconnection

提问by David

I have some working java code which does the following:

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

However, I noticed that my webserver access log contained the plaintext password for all of the users who connected. I would like to get this out of the access log, but the webserver admins claim that this needs to be changed in my code and not via webserver config.

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

I tried changing the code to the following:

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

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

Now the access log does not contain the username/password/request method. However, the webservice now throws an exception indicating that it didn't receive any username/password.

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

What did I do wrong in my client code? I also tried using "setRequestProperty" instead of "addRequestProperty" and it had the same broken behavior.

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

回答by David

I actually found the answer in another question on stackoverflow.

我实际上在关于 stackoverflow 的另一个问题中找到了答案

The correct code should be:

正确的代码应该是:

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