这是我尝试复制的curl 命令:
下面是curl请求。
curl user:password@localhost:8080/foo/bar -d property_one=value_one -d property_two=value_two -d property_three=value_three
这是 httpurlconnection 的代码
URL thisurl = new URL ("http://localhost:8080/foo");
String encoding = Base64Encoder.base64Encode("user:password");
HttpURLConnection connection = (HttpURLConnection) thisurl.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.addRequestProperty("property_one", "value_one");
connection.addRequestProperty("property_two", "value_two");
connection.addRequestProperty("property_three", "property_three");
connection.setRequestProperty ("Authorization", "Basic " + encoding);
InputStream content = (InputStream)connection.getInputStream();
在 connection.getInputStream() 行上,我收到 401 错误。我的身份验证错误吗?
最佳答案
connection.setRequestMethod("GET");
此处将方法设置为“GET”,这与 curl
中使用的方法相同。
connection.setDoOutput(true);
这里您隐式地将其设置为“POST”,这是不一样的,因此您没有任何理由期望相同的结果。
不要手动完成所有这些身份验证。使用java.net.Authenticator。
这就是它的用途。
关于java - HttpUrlConnection 身份验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32983613/