似乎方法 .connect() 不起作用

Seems method .connect() doesn't work

我正在尝试使用此代码在 运行 一些测试之前从数据库中删除用户:

URL url = new URL("someurl/remove?user=user001@mailinator.com");
HttpURLConnection huc = (HttpURLConnection)url.openConnection();
String userPassword = "is:IS!";
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());
huc.setRequestMethod("GET");
huc.setRequestProperty("Authorization", "Basic " + encoding);
huc.connect();

它对我不起作用(user001 仍存在于数据库中)。但如果我使用 .getResponseCode() 而不是 .connect(),一切正常。为什么?

因为当你打电话时

huc.connect();

您实际上并不是在调用 url。您只是打开与服务器的连接。通常你不应该调用那个方法,因为当你调用像

这样的东西时它会被调用
getInputStream(), getResponseCode(), or getResponseMessage()

在 HttpURLConnection 的 sun.net.www.protocol.http.HttpURLConnection 实现中,connect() 本身并不实际发送请求(包括身份验证、处理重定向等)。这需要调用 getInputStream(),稍后可能会调用。

如果尚未调用 getResponseCode,则调用 getInputStream。