Pergunta

Estou trabalhando em um aplicativo que precisa obter a fonte de uma página da web a partir de um link e analisar o HTML dessa página.

Você poderia me dar alguns exemplos ou pontos de partida onde procurar começar a escrever esse aplicativo?

Foi útil?

Solução

Você pode usar HttpClient Para executar um HTTP, obtenha e recupere a resposta HTML, algo assim:

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);

String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
    str.append(line);
}
in.close();
html = str.toString();

Outras dicas

eu sugeriria JSUP.

De acordo com o site deles:

Pegue a página inicial da Wikipedia, analise -a a um DOM e selecione as manchetes da seção de notícias em uma lista de elementos (amostra online):

Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
Elements newsHeadlines = doc.select("#mp-itn b a");

Começando:

  1. Download A biblioteca principal JSoup Jar
  2. Leia o livro de receitas introdução

Esta pergunta é um pouco antiga, mas achei que deveria postar minha resposta agora que DefaultHttpClient, HttpGet, etc. estão precedidos. Esta função deve obter e retornar HTML, dada um URL.

public static String getHtml(String url) throws IOException {
    // Build and set timeout values for the request.
    URLConnection connection = (new URL(url)).openConnection();
    connection.setConnectTimeout(5000);
    connection.setReadTimeout(5000);
    connection.connect();

    // Read and store the result line by line then return the entire string.
    InputStream in = connection.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder html = new StringBuilder();
    for (String line; (line = reader.readLine()) != null; ) {
        html.append(line);
    }
    in.close();

    return html.toString();
}
public class RetrieveSiteData extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
    StringBuilder builder = new StringBuilder(100000);

    for (String url : urls) {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse execute = client.execute(httpGet);
            InputStream content = execute.getEntity().getContent();

            BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
            String s = "";
            while ((s = buffer.readLine()) != null) {
                builder.append(s);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return builder.toString();
}

@Override
protected void onPostExecute(String result) {

}
}

Se você tiver uma olhada aqui ou aqui, você verá que não pode fazer isso diretamente com a API Android, você precisa de um Librairy externo ...

Você pode escolher entre os 2 aqui está o HEREABOVE se você precisar de um Libribrair externo.

Chame como

new RetrieveFeedTask(new OnTaskFinished()
        {
            @Override
            public void onFeedRetrieved(String feeds)
            {
                //do whatever you want to do with the feeds
            }
        }).execute("http://enterurlhere.com");

Recuperarfeedtask.class

class RetrieveFeedTask extends AsyncTask<String, Void, String>
{
    String HTML_response= "";

    OnTaskFinished onOurTaskFinished;


    public RetrieveFeedTask(OnTaskFinished onTaskFinished)
    {
        onOurTaskFinished = onTaskFinished;
    }
    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... urls)
    {
        try
        {
            URL url = new URL(urls[0]); // enter your url here which to download

            URLConnection conn = url.openConnection();

            // open the stream and put it into BufferedReader
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String inputLine;

            while ((inputLine = br.readLine()) != null)
            {
                // System.out.println(inputLine);
                HTML_response += inputLine;
            }
            br.close();

            System.out.println("Done");

        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return HTML_response;
    }

    @Override
    protected void onPostExecute(String feed)
    {
        onOurTaskFinished.onFeedRetrieved(feed);
    }
}

ONTASKFINISED.Java

public interface OnTaskFinished
{
    public void onFeedRetrieved(String feeds);
}

Um do outro ASSIM A resposta post me ajudou. Isso não lê linha por linha; com o número de arquivo html, tinha uma linha nulo entre. Como o pré -requisito adiciona essa dependência das configurações do projeto "com.koushikdutta.ion: ion: 2.2.1" implementar este código em ASYNCTASK. Se você quiser o retorno -algo- Para estar no encadeamento da interface do usuário, passe -o para uma interface mútua.

Ion.with(getApplicationContext()).
load("https://google.com/hashbrowns")
.asString()
.setCallback(new FutureCallback<String>()
 {
        @Override
        public void onCompleted(Exception e, String result) {
            //int s = result.lastIndexOf("user_id")+9;
            // String st = result.substring(s,s+5);
           // Log.e("USERID",st); //something

        }
    });
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top