HttpClient follow redirect [duplicate]
Asked Answered
D

1

6

I am currently working on little project. The aim of the project is to log in to a website and get/handle the information on the site. Moreover, I would like to open some links and search through them as well.

The server side looks like this:

You need to login to a php site. When sucessfully login you get a session and will be redirected to foo.username.bar.php (changed).

With this code:

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();
            }
        }
    }
}

I sucessfully logged into the website. However, I can only see the page source of the php user confirmation site which tells me that I was sucessfully logged in and will be redirected.

Now I actually want to see the page source where I was redirected too and keep the connection in order to open some more links on that page.

Do you guys have an Idea how I can solve this?

Disservice answered 19/8, 2013 at 17:53 Comment(0)
S
2

You need to follow the redirect (status 302) returned by the response. Check out this answer.

Sachs answered 19/8, 2013 at 17:57 Comment(1)
Thanks. I checked the status code which was returned. Its 200. So I figured the redirect does not happen via php but instead via html (redirect after 2s). So I simply extracted the URL and achieved my goal.Disservice

© 2022 - 2024 — McMap. All rights reserved.