【问题标题】:I'm getting an IllegalStateException: Already connected and I cannot figure out why我收到 IllegalStateException:已经连接,但我不知道为什么
【发布时间】:2015-07-14 05:59:32
【问题描述】:

所以我正在尝试编写一个连接到站点并从源代码中提取数据的程序。每当我调用此方法时,一旦它到达connection.setRequestProperty("Cookie", cookie); 行,它就不会再继续执行并吐出“IllegalStateException:已连接”。我正在尝试循环浏览 123 个不同的 URL,因此每次调用该方法时 URL 都会更改,所以我不太确定为什么当我尝试重新连接到不同的 URL 时它告诉我它已经连接。我试过到处寻找解决方案,但找不到。你们中的任何人都可以帮忙吗?谢谢!

private void getUrlData(String u, String championName) throws IOException {
    List<String> data = new ArrayList<String>();
    try {
        BufferedWriter out = new BufferedWriter(new FileWriter("Other Stuff/Champion Data Test.txt"));
        out.write(championName);
        out.newLine();

        URL url = new URL(u);
        URLConnection connection = url.openConnection();
        String cookie = connection.getHeaderField("Set-Cookie");

        connection.setRequestProperty("Cookie", cookie);
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36");
        connection.connect();

        Scanner in = new Scanner(connection.getInputStream());

        String inputLine;
        while(in.hasNext()) {
            inputLine = in.nextLine();
            if(inputLine.contains("stat-label")) {
                out.write(in.nextLine());
                in.nextLine();
                in.nextLine();
                out.write(" " + in.nextLine());
            }
        }
    } 
    catch(Exception e) {
        System.out.println(e);
    }
}

【问题讨论】:

  • 你能把代码贴在你调用这个方法的地方吗?

标签: java cookies illegalstateexception


【解决方案1】:

我发现了问题,但我解决这个问题引起了新的问题。问题是我使用connection.getHeaderField("Set-Cookie")的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    相关资源
    最近更新 更多