简体   繁体   English

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

[英]Seems method .connect() doesn't work

I'm trying to use this code to remove a user from a database before running some tests: 我正在尝试使用此代码在运行某些测试之前从数据库中删除用户:

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();

It doesn't work for me ( user001 is still presented in database). 它对我不起作用( user001仍然存在于数据库中)。 But all works fine if I use .getResponseCode() instead of .connect() . 但是,如果使用一切工作正常.getResponseCode()代替.connect() Why? 为什么?

Because when you call 因为你打电话的时候

huc.connect();

you are not actually calling the url. 你实际上并没有调用网址。 You are just opening connection to the server. 您只是打开与服务器的连接。 And normally you shouldn't call that method because that is called when you call something like 通常你不应该调用那个方法,因为当你调用类似的东西时会调用它

getInputStream(), getResponseCode(), or getResponseMessage()

In the sun.net.www.protocol.http.HttpURLConnection implementation of HttpURLConnection, connect() by itself does not actually send the request (including authenticate, handle re-directs, etc.). sun.net.www.protocol.http.HttpURLConnection实现HttpURLConnection,connect()本身并不实际发送请求(包括authenticate,handle re-directs等)。 That requires a call to getInputStream(), which may come later. 这需要调用getInputStream(),这可能会在以后发生。

The call to getResponseCode calls getInputStream if has not been called already. 如果尚未调用getResponseCode,则调用getInputStream。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM