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

标签 java http url connection

考虑下面的代码。由于我正在执行 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/

相关文章:

java - 使用 currenttimemillis() 函数打印出时间

java - 关于 &(bit and) 运算符

java - twitter streaming api - 在 http post 请求中设置过滤器(apache httpcomponents)

路由辅助函数的 http 动词

php - '?doing_wp_cron='

javascript - Angularjs 传递查询参数

ios - 如何在没有图像时隐藏 UIImageView 的 View

java - 我应该将我的 Angular 文件放在同一个 JEE 项目中吗?

java - 无法使用 org.json 库解析 json 数组?

javascript - 你什么时候想要更多/更少的http请求?