HttpUrlConnection addRequestProperty方法未传递参数 [英] HttpUrlConnection addRequestProperty Method Not Passing Parameters

查看:194
本文介绍了HttpUrlConnection addRequestProperty方法未传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些可以执行以下操作的Java代码:

I have some working java code which does the following:

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服务器配置进行更改.

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

现在,访问日志中不包含用户名/密码/请求方法.但是,该Web服务现在会引发异常,表明它没有收到任何用户名/密码.

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.

我的客户代码有什么错?我还尝试使用"setRequestProperty"代替"addRequestProperty",它具有相同的损坏行为.

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

推荐答案

我实际上在另一个关于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

这篇关于HttpUrlConnection addRequestProperty方法未传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆