How to get html code through a url in android studio

Asked

Viewed 76 times

1

I would like to do as I get html code from a site using android studio. This is the code I did, but it does not returns anything.

private static String pegarURL(String a) {
    StringBuilder b = new StringBuilder();

    try {
        URL url = new URL(a);

        URLConnection urlConnection = url.openConnection();

        BufferedReader bufferedReader =
                new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            b.append(line + "\n");
        }

        bufferedReader.close();
    } catch(Exception e) {

        e.printStackTrace();
    }

    return b.toString();

}

String h = pegarURL("https://www.google.com/");

1 answer

1


The most practical way I’ve found of doing this is as follows. Add in your Radle dependencies the code below:

implementation 'com.koushikdutta.ion:ion:2.1.8'

From Sync, then import the two libraries below

import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;

And use the following code to get your HTML code

Ion.with(getApplicationContext()).load("http://www.google.com").asString().setCallback(new FutureCallback<String>() { 
            @Override
            public void onCompleted(Exception e, String result) {
                Log.i("RESULTADO",result); // Aqui você trabalha com a resposta
            }
        });
  • 1

    Thanks, I used several forms, but none worked. This one served me well. Thanks!

  • You are welcome! I had already searched several, I found some that worked, but I had to use many more codes.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.