gpt4 book ai didi

java - 如果我在创建对象时已经打开连接,是否需要执行 HTTPUrlConnection.connect() ?

转载 作者:行者123 更新时间:2023-12-02 07:12:04 25 4
gpt4 key购买 nike

考虑下面的代码。由于我正在执行 url.openConnection(),connection.connect 是否多余?如果是,那么为什么我们有 .connect() 方法?是为了关闭连接后重新连接吗?

URL url;
url = new URL(
"http://api.longurl.org/v2/expand?format=json&title=1&user-agent=TwitterProject&url="
+ someURL);
HttpURLConnection connection;
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line = null;
String full = "";
while ((line = in.readLine()) != null) {
full = full + line;
}
jsonresponse = JSONObject.fromObject(full);

最佳答案

public abstract void connect() throws IOException

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established. If the connect method is called when the connection has already been opened (indicated by the connected field having the value true), the call is ignored.

在您的情况下,调用将被忽略。

 connection = (HttpURLConnection) url.openConnection();// already established connection.

关于java - 如果我在创建对象时已经打开连接,是否需要执行 HTTPUrlConnection.connect() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15387879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com