首页 > 解决方案 > 如何在java中使用一个httpURLConnection浏览多个url

问题描述

我正在尝试连接到一个网站并通过整个网站的不同页面发送许多不同的帖子请求。我已经到了第一步:连接网站。但现在,我需要更改请求 url 并保持相同的 httpURLConnection。

现在我的代码是:

//openning the connection to the website
URL url = new URL("http://path/to/the/website");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        //preparing the post arguments
        Map<String, Object> params = new HashMap<>();
        params.put("Action", "connect_user");
        params.put("login", "login");
        params.put("password", "password");

        StringBuilder sb = new StringBuilder();
        for (Entry<String, Object> e : params.entrySet()) {
            if (sb.length() != 0)
                sb.append('&');
            sb.append(URLEncoder.encode(e.getKey(), "UTF-8"));
            sb.append('=');
            sb.append(URLEncoder.encode(String.valueOf(e.getValue()), "UTF-8"));
        }
        //writing the request and sending
        BufferedOutputStream writer = new BufferedOutputStream(conn.getOutputStream());
        writer.write(sb.toString().getBytes(Charset.forName("UTF-8")));
        writer.flush();

在这一步,我已连接并成功登录。我现在需要做的是将相同的连接重定向到第二个 url。谢谢。

标签: javahttpurlconnection

解决方案


推荐阅读