3

I've been searching the simplest way to get Html code to String for some time now. I just need to fetch it so i can move forward with my project.

I tried:

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
    Request request = new Request.Builder()
            .url(url)
            .build();

    Response response = client.newCall(request).execute();
    return response.body().string();
}

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text = (TextView) findViewById(R.id.text);

    String html= null;
    try {
        html = run("http://google.com");
    } catch (IOException e) {
        e.printStackTrace();
    }

    text.setText(html);
}

}

I got Error android.os.NetworkOnMainThreadException.

I just started developing in Android studio and I'm not an expert in Java either. I would like if someone would explain what i need to do, with examples preferably. thank you in advance

JuliusCezarus
  • 53
  • 1
  • 8
  • 1
    You are calling `execute()`, which is going to execute the request on the current thread. That thread appears to be the main application thread, and so you will crash. Use `enqueue()`, rather than `execute()`, to have OkHttp execute the HTTP request on a background thread. – CommonsWare Dec 27 '16 at 19:12
  • Can someone help and write why isnt this working? http://stackoverflow.com/a/41351476/7313961 – JuliusCezarus Dec 29 '16 at 19:55

2 Answers2

4

As @CommonsWare and @christian have already said, you need to make network operations in the background and for this aim Okhttp has a special method enqueue(). This will create a background thread for you and simplify your work.

In your case, change the lines inside run() method to these:

String run(String url) throws IOException {

    String result = "";

    Request request = new Request.Builder()
        .url(url)
        .build();

    Response response = client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            // failure case
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            // success case
            result = response.body().string();
        }
    });
}
Marat
  • 6,142
  • 6
  • 39
  • 67
0

You need to make network operations in background thread otherwise, you will get the exceptions. Android make it mandatory because network call takes a bit time and the UI-Thread will freeze.

Please refer https://github.com/square/okhttp/wiki/Recipes#asynchronous-get and https://stackoverflow.com/a/6343299/1947419

Community
  • 1
  • 1
christian
  • 445
  • 1
  • 3
  • 12