0

当我登录网页然后解析 html 时,我有一个 bash 脚本。我使用的命令是 wget:

wget --save-cookies=cookies.txt --post-data "uid=USER&pass=PWD" http://www.spanishtracker.com/login.php

wget --load-cookies=cookies.txt "http://www.spanishtracker.com/torrents.php"  -O OUTPUT

现在,我正在尝试用 Java 制作这些。首先,我正在尝试发布请求,但是当我执行输出时,我登录时并没有给出。这些是Java的代码:

try {
        data = URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode("USER", "UTF-8");
        data += "&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode("PASS", "UTF-8");

                // Send the request
                URL url = new URL("http://www.spanishtracker.com/index.php");
                URLConnection conn = url.openConnection();


                conn.setDoOutput(true);

                OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

                //write parameters
                writer.write(data);
                writer.flush();

                // Get the response
                StringBuffer answer = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    answer.append(line);
                }
                writer.close();
                reader.close();
                // temporary to build request cookie header
                StringBuilder sb = new StringBuilder();

                // find the cookies in the response header from the first request
                List<String> cookies = conn.getHeaderFields().get("Set-Cookie");
                if (cookies != null) {
                    System.out.println("Hay cookies para guardar");
                    for (String cookie : cookies) {
                        if (sb.length() > 0) {
                            sb.append("; ");
                        }

                        // only want the first part of the cookie header that has the value
                        String value = cookie.split(";")[0];
                        sb.append(value);
                    }
                }

请问你能帮帮我吗。非常感谢和对不起我的英语!

4

1 回答 1

0

使用 apache HttpClient 库链接

于 2012-10-30T17:48:42.947 回答