HttpClient 跟随重定向

chr*_*z42 5 php java session web apache-commons-httpclient

我目前正在做一个小项目。该项目的目的是登录网站并获取/处理网站上的信息。此外,我想打开一些链接并搜索它们。

服务器端看起来像这样:

您需要登录到一个 php 站点。成功登录后,您将获得一个会话并将被重定向到 foo.username.bar.php(已更改)。

使用此代码:

BufferedReader in = null;
    String data = null;
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("username",  user));
        nameValuePairs.add(new BasicNameValuePair("passwort", pass));

        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost(website);
        request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity()
                .getContent()));
        StringBuffer sb = new StringBuffer("");
        String l = "";
        String nl = System.getProperty("line.separator");
        while ((l = in.readLine()) != null) {
            sb.append(l + nl);
        }
        in.close();
        data = sb.toString();
        return data;
    } finally {

        if (in == null) {
            try {
                in.close();
                return "ERROR";
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我成功登录了该网站。但是,我只能看到php用户确认站点的页面源,它​​告诉我我已成功登录并将被重定向。

现在我实际上想查看我被重定向的页面源并保持连接以便在该页面上打开更多链接。

你们有什么想法我该如何解决这个问题?

jtr*_*ini 2

您需要遵循响应返回的重定向(状态 302)。看看这个答案

  • 谢谢。我检查了返回的状态代码。它是200。所以我认为重定向不是通过php发生的,而是通过html发生的(2秒后重定向)。于是我简单的提取了URL就达到了我的目的。 (2认同)