HttpClient跟随重定向

6
我目前正在做一个小项目。该项目的目的是登录一个网站,获取/处理网站上的信息。此外,我还想打开一些链接并进行搜索。
服务器端看起来像这样:
您需要登录到一个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();
            }
        }
    }
}

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

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

你们有什么办法可以解决这个问题吗?

1个回答

2
你需要按照响应返回的重定向(状态码302)进行跟进。请参考这个答案。

2
谢谢。我检查了返回的状态码,是200。所以我想重定向不是通过php而是通过html实现的(2秒后重定向)。因此,我只需提取URL即可实现我的目标。 - chrizz42

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接