【问题标题】:Is it required to do a HTTPUrlConnection.connect() if I am already opening a connection when I create an object?如果我在创建对象时已经打开连接,是否需要执行 HTTPUrlConnection.connect()?
【发布时间】:2013-03-13 14:18:48
【问题描述】:

考虑以下代码。由于我正在执行 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);

【问题讨论】:

    标签: java http url connection


    【解决方案1】:

    public abstract void connect() throws IOException

    打开指向此 URL 引用的资源的通信链接,如果 这种联系尚未建立。如果连接 当连接已经打开时调用方法 (由值为 true 的连接字段表示),调用是 忽略。

    在您的情况下,呼叫被忽略。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2014-06-30
      • 2019-04-21
      • 1970-01-01
      • 2017-12-01
      相关资源
      最近更新 更多