Java HttpUrlConnection身份验证不工作
下面是我尝试复制的curl命令: 下面是curl请求Java HttpUrlConnection身份验证不工作,java,curl,httpurlconnection,Java,Curl,Httpurlconnection,下面是我尝试复制的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 enc
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错误。身份验证是否有误?
401错误
原因是未进行用户身份验证。可能是您未正确编码身份验证标头。使用这个代码,它对我有用。你可以在这里获得详细信息
这里您将方法设置为“GET”,这与您在curl
中使用的方法相同
connection.setDoOutput(true);
在这里,您隐式地将其设置为“POST”,这是不同的,因此您没有任何理由期望得到相同的结果
不要手动执行所有这些身份验证。使用
java.net.Authenticator。
这就是它的用途。不知道这是否重要,但您的URL不同。您是否尝试过不使用连接。setDoOutput(true)代码>?get请求不允许输出。1)cURL请求是POST
请求。任何带有-d
的请求都将隐式地发出POST
。2) 数据应该作为url编码的表单参数在请求体中发送,而不是在请求属性中发送。3) 内容类型
标题在cURL请求中隐式设置为application/x-www-form-urlencoded
。在Java代码中也应该这样做。
connection.setRequestMethod("GET");
connection.setDoOutput(true);