Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient follow redirect [duplicate]

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?

like image 761
chrizz42 Avatar asked Aug 19 '13 17:08

chrizz42


1 Answers

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

like image 145
jtravaglini Avatar answered Oct 14 '22 00:10

jtravaglini