【问题标题】:HttpClient follow redirect [duplicate]HttpClient跟随重定向[重复]
【发布时间】:2023-03-12 04:36:02
【问题描述】:

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

服务器端是这样的:

您需要登录到一个 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 用户确认站点的页面源,它​​告诉我我已成功登录并将被重定向。

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

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

【问题讨论】:

    标签: java php session web apache-commons-httpclient


    【解决方案1】:

    您需要遵循响应返回的重定向(状态 302)。查看this answer

    【讨论】:

    • 谢谢。我检查了返回的状态码。它的 200。所以我认为重定向不是通过 php 发生的,而是通过 html 发生的(2 秒后重定向)。所以我简单地提取了 URL 并实现了我的目标。
    猜你喜欢
    • 1970-01-01
    • 2010-11-24
    • 2012-01-05
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多