oli206
oli206

Reputation: 453

Connect to web that requires user/password

I'm a bit new to Java and more to connections stuff with it. I'm trying to create a program to connect to a website ("www.buybackprofesional.com") where I would like to download pictures and get some text from cars (after the login you have to enter a plate number to access a car's file).

This is what I have right now, but it always says that the session has expired, I need a way to login using the username and password of the mainpage, am I right? can someone give me some advice? Thanks

Note: I want to do it in Java, maybe I was not clear in the question.

        //URL web = new URL("http://www.buybackprofesional.com/DetallePeri.asp?mat=9073FCV&fec=27/07/2010&tipo=C&modelo=4582&Foto=0");
        URL web = new URL("http://www.buybackprofesional.com/");
        HttpURLConnection con = (HttpURLConnection) web.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)");
        con.setRequestProperty("Pragma", "no-cache");
        con.connect();
              BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }                  

A colleage helped me with this so I'll post the code that works:

public static URLConnection login(String _url, String _username, String _password) throws IOException, MalformedURLException {

    String data = URLEncoder.encode("Usuario", "UTF-8") + "=" + URLEncoder.encode(_username, "UTF-8");
    data += "&" + URLEncoder.encode("Contrase", "UTF-8") + "=" + URLEncoder.encode(_password, "UTF-8");

    // Send data
    URL url = new URL(_url);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();
    wr.close();
    return conn;
}

This will submit the form info on the page I need and after that, using cookies I can stay connected!

Upvotes: 3

Views: 3940

Answers (1)

John Vint
John Vint

Reputation: 40256

To connect to a website using java consider using httpunit or httpcore (offered by apache). They handle sessions much better then you (or I) could do on your own.

Edit: Fixed the location of the link. Thanks for the correction!

Upvotes: 1

Related Questions