Pobieranie zrodla strony

0

Witam.
Mam nastepujacy problem.Potrzebuje pobrac kod zrodlowy strny.Korzystam w tym celu z napisanego juz kiedys kodu:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;


public class java 
{
    public static String pobierz(String link) throws MalformedURLException, IOException
    {
        String source = "";
        URL akt = new URL(link);
        BufferedReader in = new BufferedReader(new InputStreamReader(akt.openStream(),"utf-8"));
        String linia;
        while ((linia = in.readLine()) != null) 
        {source += linia+"\n";}
        in.close();
        return source;
    }

    public static void main(String[] args) {
        try {System.out.println(pobierz("http://www.wp.pl"));} 
        catch (MalformedURLException ex) {
        	ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

I wszystko jest pieknie, niestety problem pojawia sie gdy chce pobrac zrodlo stronki z autoryzacja.
Tak konkretnie to chodzi mi o witryne www.gfsignals.com.
Czy ktos wie moze jak przerobic powyzszy kod,zeby mozna bylo go zastosowac do podanej stronki. A jesli jest to niemozliwe,to jak sie do niej dobrac?
Dzieki za wszystkie sugestie.
Pozdrawiam.

0

Ja czytam tak:
host to JTextField gdzie użytkownik wpisuje adres
contents to JtextArea gdzie program wpisuje odczytane źródło

    public void actionPerformed(ActionEvent ae)
    {
        String s=host.getText();
        String zapytanie="GET http://"+s+"/ HTTP/1.1"
        +"\r\n"+"Host: www.dom.pl"
        +"\r\n"+"User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; pl; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12"
        +"\r\n"+"Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
        +"\r\n"+"Accept-Language: pl,en-us;q=0.7,en;q=0.3"
        +"\r\n"+"Accept-Encoding: gzip,deflate"
        +"\r\n"+"Acept-Charset: ISO-8859-2,utf-8;q=0.7,*;q=0.7"
        +"\r\n"+"Keep-Alive: 300"
        +"\r\n"+"Proxy-Connection: keep-alive"
        +"\r\n\r\n";
        try
        {
            socket=new Socket(s,80);
            StringBuffer bufor=new StringBuffer();
            BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter out=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String linia;;
            out.write(zapytanie);
            out.flush();
            while ((linia=in.readLine())!=null)
            {
                bufor.append(linia+"\n");
            }
            contents.setText(bufor.toString());
            host.selectAll();
        }
        catch(Exception e)
        {
            contents.setText("Błąd: "+e.toString());
        }
    }

Interesująca Cię strona zaczyna się tak:

HTTP/1.1 200 OK
Date: Sat, 07 Mar 2009 1817 GMT
Server: Apache/1.3.37 (Unix) PHP/4.4.2 mod_ssl/2.8.28 OpenSSL/0.9.8j
X-Powered-By: PHP/4.4.2
Transfer-Encoding: chunked
Content-Type: text/html

10b9

<html> <head> <title>Global Forex Signals - Real Time Forex Signals, Forex Predictions, Forex Recommendations, Forex Signals, Managed Forex, Forex Forecasts, Forex Alerts, Forex Training</title> <meta name="description" content="GFSignals.com - Forex Signals, Automated Forex, Managed Forex, Forex Forecasts, Forex Predictions, Forex Recommendations, Forex Alerts, Forex Training, Forex Forum, Forex Chat"> <meta name="keywords" content="Forex Signals, Managed Forex, Automated Forex Trading, Forex Forecasts, Forex Predictions, Forex Recommendations, Forex Alerts, Forex Training, Forex Forum, Forex Chat"> <meta name="rating" content="Finance">
0

Jeśli chodzi o takie logowanie: http://en.wikipedia.org/wiki/Basic_access_authentication

To wystarczy przed odebraniem danych wysłać dodatkowy nagłówek HTTP:

public static String pobierz(String link) throws MalformedURLException, IOException
{
    String source = "";
    URL akt = new URL(link);

    URLConnection connection = akt.openConnection();
    /*
     * For example, given the user name Aladdin and password open sesame, 
     * the string Aladdin:open sesame is Base64 encoded, resulting in QWxhZGRpbjpvcGVuIHNlc2FtZQ==
     */
    byte[] buffer = new String("Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==").getBytes();
    connection.setDoOutput(true);
    OutputStream out = connection.getOutputStream();
    out.write(buffer);
    out.flush();

    BufferedReader in = new BufferedReader(new InputStreamReader(akt.openStream(),"utf-8"));
    String linia;
    while ((linia = in.readLine()) != null)
    {source += linia+"\n";}
    in.close();
    return source;
}

Tylko musisz sobie poszukać jak wygenerować w javie Base64

0

@abe, autor pytał jak pobrać źródło, a nie jak się zalogować. Mój kod pobiera źródło.

0

Dzieki wielkie,w szczegolnosci bogdans.
Co prawda jeszcze nie sprawdzilem kodu,ale to kwestia najblizszych 20 min :)
Interesuje mnie tylko to zapytanie.Tak je przegladam i doszedlem do wniosku,ze kod wykorzystuje przegladarke do polaczenia.Wiec wnioskuje,ze uzytkownik niezaopatrzony z Firefoxa nic nie zdziala?

0

No i jednak nie dziala. Te zrodlo co pobrales bylo z podstrony bez autoryzacji. Z tym juz jest zwracany error http://www.gfsignals.com/members/sgnhist.php .
A i ze zwykla strona jakies krzaczki mi w konsoli zwracalo.

0

Ok,posiedzialem w nocy i znalazlem rozwiazanie, sprawdza sie doskonale, a kod czytelny jest:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;

public class AuthDemo {
  public static void main(String args[]) throws MalformedURLException,
      IOException {
    String urlString = "";
    String username = "";
    String password = "";
    Authenticator.setDefault(new MyAuthenticator(username, password));
    URL url = new URL(urlString);
    InputStream content = (InputStream) url.getContent();
    BufferedReader in = new BufferedReader(new InputStreamReader(content));
    String line;
    while ((line = in.readLine()) != null) {
      System.out.println(line);
    }
    System.out.println("Done.");
  }

  static class MyAuthenticator extends Authenticator {
    private String username, password;

    public MyAuthenticator(String user, String pass) {
      username = user;
      password = pass;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
      System.out.println("Requesting Host  : " + getRequestingHost());
      System.out.println("Requesting Port  : " + getRequestingPort());
      System.out.println("Requesting Prompt : " + getRequestingPrompt());
      System.out.println("Requesting Protocol: "
          + getRequestingProtocol());
      System.out.println("Requesting Scheme : " + getRequestingScheme());
      System.out.println("Requesting Site  : " + getRequestingSite());
      return new PasswordAuthentication(username, password.toCharArray());
    }
  }
}

Pozdrawiam.

0

W jaki sposób zmodyfikować ten kod aby działał pod "https" ? np żeby ściągał źródło strony pocztowej już po zalogowaniu ( https://konto.onet.pl/login.html?client_id=poczta.onet.pl.front&ticket=1412951085 )

1 użytkowników online, w tym zalogowanych: 0, gości: 1