HttpUrlConnection 身份验证不起作用

HttpUrlConnection authentication not working

这是我尝试复制的 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 错误。我是不是认证错了?

401 error 因为关闭用户 authentication.It 可能是因为您 没有正确编码身份验证 header 。使用此适用于 me.you 的代码可以在此处获取详细信息 here

 URL url = new URL ("http://localhost:8080/foo");
 String encoding = org.apache.catalina.util.Base64.encode(credentials.getBytes("UTF-8"));

URLConnection uc = url.openConnection();
uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
connection.setRequestMethod("GET");

此处您将方法设置为 "GET",这与您在 curl 中使用的方法相同。

connection.setDoOutput(true);

此处您将其隐式设置为 "POST",这并不相同,因此您没有任何理由期待相同的结果。

不要手动完成所有这些身份验证。使用java.net.Authenticator.就是这个意思